问题
I was wondering whether I should use asynchronous calls on my website or not. I know to specify this explicitly I need to use
$.ajax
however initially I tried using $.get
and although the server had to return lots of information, my browser didn't stuck and I could navigate without any problems.
I searched a little bit online about it, however I'm still not 100% certain about the difference between the two.
If $.get
is asynchronous then what's the point of $.ajax
? And if it's not, then again seeing how I had no navigation problems with $.get
, what's the point of using $.ajax
?
thanks in advance
回答1:
Yes, $.get is asynchronous. From the documentation:
This is a shorthand Ajax function, which is equivalent to:
$.ajax({ url: url, data: data, success: success, dataType: dataType });
...and as that doesn't have the async
option, async
defaults to true
. (Note that async
will be going away entirely in a future version of jQuery; it will always be true.)
If
$.get
is asynchronous then what's the point of$.ajax
?
$.ajax
gives you control over lot more options. $.get
is just a shortcut.
回答2:
$.get is simply a shorthand for:
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
回答3:
As stated by the jQuery
documentation, $.get
is a convenience wrapper for the more low-level $.ajax
.
回答4:
$.ajax with GET method, How about this with a promise object?
function showResults(name) {
var deferred = $.Deferred, requests = [];
requests.push($.ajax({url:"/path/to/uri/?name=" + name, type: "GET", async: false}).done(function(d) {
//alert or process the results as you wish
}));
$.when.apply(undefined, requests).then(function(d) { console.log(d); /*var d is a promised late return */ deferred.resolve(); });
return deferred.promise();
}
he returned promise object can also be used with $.when(showResults('benjamin')).done(function() { });
for post modifications (like chart/graph settings etc). totally reusable. You may also put this function in a loop of $.deferred requests like,
function updateResults() {
var deferred = $.Deferred, requests = [];
requests.push($.ajax(url:"/path/to/names/?nameArr=" + jsonArrOfNames, type: "GET", async: false}).done(function(res) { requests.push(showResults(res[0]));}) );
$.when.apply($, requests).then(function(d) { console.log(d); /*var d is a promised late return */ deferred.resolve(); });
return deferred.promise();
}
来源:https://stackoverflow.com/questions/13671798/is-get-of-jquery-asynchronous