Reputation: 232
I have two questions about jQuery AJAX.
1) Is there any difference between $.load()
and $.ajax() used with type: 'GET'
? They seem to do the same job.
2) This question is related to the code below. What happens, if I don't write the "type: GET" line at all? Does it mean the same thing?
$(document).ready(function() {
$('#update').click(function() {
$.ajax({
type: 'GET',
url: 'hello-ajax.html',
dataType: 'html',
success: function(html, textStatus) {
$('body').append(html);
},
error: function(xhr, textStatus, errorThrown) {
alert('An error occurred! ' + ( errorThrown ? errorThrown :
391
xhr.status );
}
});
});
});
Is it any different from
$(document).ready(function() {
$('#update').click(function() {
$.ajax({
url: 'hello-ajax.html',
dataType: 'html',
success: function(html, textStatus) {
$('body').append(html);
},
error: function(xhr, textStatus, errorThrown) {
alert('An error occurred! ' + ( errorThrown ? errorThrown :
391
xhr.status );
}
});
});
});
Upvotes: 0
Views: 110
Reputation: 21
Extracted from jQuery manual .load
This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched element to the returned data. This means that most uses of the method can be quite simple:
$( "#result" ).load( "ajax/test.html" );
If no element is matched by the selector — in this case, if the document does not contain an element with id="result" — the Ajax request will not be sent.
Upvotes: 2
Reputation: 3592
I guess the difference is that .load() function allows to target the result into a DOM element. Like so
$( "#target" ).load( "source.html" );
And the ajax() method returns an object (eg. JSON) that can be the manipulated. etc. apart from more attributes.
Upvotes: 0
Reputation: 1751
This is straight from jQuery Docs (http://api.jquery.com/load/)
The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.
Since $.get()
is simply the $.ajax()
shorthand for "data: 'Get'", it would appear the only major difference is the ability to do the aforementioned (import partial sections of a document).
Edit: To answer your second question, GET is the default data type for the $.ajax() call, POST being your other option. You can read a bit about POST here (http://api.jquery.com/jQuery.post/)
Upvotes: 3