23

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

4

4 回答 4

35

是的,$.get是异步的。从文档中:

这是一个简写的 Ajax 函数,相当于:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

...并且由于没有async选项,因此async默认为true. (请注意,这async将在 jQuery 的未来版本中完全消失;它将永远是真的。)

如果$.get是异步的,那有什么意义$.ajax呢?

$.ajax让您控制更多选项。$.get只是一个捷径。

于 2012-12-02T17:35:04.533 回答
3

$.get只是以下的简写:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
于 2012-12-02T17:35:24.490 回答
0

jQuery 文档所述,$.get它是更底层的便捷包装器$.ajax

于 2012-12-02T17:36:41.680 回答
0

$.ajax 带有 GET 方法,这个带有 Promise 对象怎么样?

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();

    }

他返回的承诺对象也可以用于$.when(showResults('benjamin')).done(function() { });后期修改(如图表/图形设置等)。完全可重复使用。您也可以将此函数放在 $.deferred 请求的循环中,例如,

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();
            }
于 2019-03-11T02:32:52.843 回答