在所有ajax调用(ajax调用的数量是动态的)收到响应后,调用函数是JQuery

时间:2016-10-14 04:15:25

标签: javascript jquery ajax

HTML: -

结果

使用Javascript: -

$(document).ready(function(){
$("#result").html("function started here");
var requests = Array();
requests.push($.get('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA'));
requests.push($.get('https://maps.googleapis.com/maps/api/geocode/json?address=EGL, Bangalore'));
var defer = $.when.apply($, requests);
  console.log(defer);
defer.done(function(){
$("#result").html("Completed");
    // This is executed only after every ajax request has been completed
    $.each(arguments, function(index, responseData){

     // alert(index);
     $("#result").html(responseData);
        // "responseData" will contain an array of response information for each specific request
    });

});
  });

上述代码段仅在所有ajax调用返回"成功"响应。有什么方法我可以知道所有ajax调用是否得到响应,可能是"成功" /"失败"

1 个答案:

答案 0 :(得分:0)

你可以ajaxStart,ajaxStop,ajaxError,ajaxSuccess。

 $(document).ajaxStart(function () {
            //when ajax start
        }).ajaxStop(function () {
           //when ajax stop
        }).ajaxError(function () {
            //when ajax error
        }).ajaxSuccess(function () {
        // when ajax success
    });

这将触发每个ajax调用。