3

在页面加载时,我需要调用 API。当所有 AJAX 调用完成(完成)后,我想要解锁 UI。问题是我不知道我会调用多少次 API。可能是一次或十次。

我的代码:

$(document).ready(function () {

           callAPI(yourApiKey);
});

和功能:

function getRates(yourAPIKey, contractCode, startDate, endDate) {
// I did cut some code here
 $.ajax({   
     url: ratesEnquiry,
     type: 'GET',
     dataType: "jsonp",
     jsonp: "callback",
     complete: function (response, responseCode) {       
     },
     success: function (json) {
     $.each(json, function (index, value) {
             populateValues("rate", this.ContractCode, this.RoomTypeCode, this.Date.substr(0, 10), this.RoomPrice);
             populateValues("hrate", this.ContractCode, this.RoomTypeCode, this.Date.substr(0, 10), this.RoomPrice);

             });
         }
     });
 }



function getAvailability(yourAPIKey, contractCode, startDate, endDate) {
    // I've cut off some code here as well
    $.ajax({
    url: availabilityEnquiry,
    type: 'GET',
    dataType: "jsonp",
    jsonp: "callback",
    //jsonpCallback: "jsonpCallback",
    complete: function (json, responseCode) {
        //console.log(response); console.log(responseCode);
        //alert("complete");           
    },
    success: function (json) {

        $.each(json, function (index, value) {
             populateValues("avail", this.ContractCode, this.RoomTypeCode, this.Date.substr(0, 10), this.Quantity);
             populateValues("havail", this.ContractCode, this.RoomTypeCode, this.Date.substr(0, 10), this.Quantity);                      
            // alert(this.RoomPrice);
            });

        }
    });
}


function callAPI(yourAPIKey) {

     // I've cut off some code here

     $.blockUI({ message: '<span class="loader green" original-title="1Loading, please wait…"></span><h3> Please wait...</h3>' });
     $.ajax({
         url: enquiry,
         type: 'GET',
         dataType: "jsonp",
         jsonp: "callback",
         complete: function (response, responseCode) {
         },
         success: function (json) {
             $.each(json.Contracts, function (index, contract) {
                ContractsArray[Count] = contract.ContractCode;
                Count++;

             });
             for(var i = 0; i < Count; i++){

                 getAvailability(yourAPIKey, ContractsArray[i], startDate, endDate);
                 getRates(yourAPIKey, ContractsArray[i], startDate, endDate);

             }
         }
     });
    }

我可以使用 ajaxStop 或 ajaxComplete 来解决这个问题吗?

4

2 回答 2

5

使用 counter 并检查是否每次调用都向该计数器添加 1 和每次完成减 1 到该计数器,如果计数器将为 0,则您知道所有 api 调用都已完成简单示例:

var calls = 0;
function makeCall(url) {
   calls++;
   $.ajax({
      complete: function(resp) {
          calls--;
      }
   });
}
于 2012-08-15T15:46:37.330 回答
0

.ajaxComplete 应该可以工作 它为 ajax 请求何时完成注册一个处理程序。本质上,只要 ajax 请求完成,就会调用此处理程序。

为什么你会认为它不起作用?

http://api.jquery.com/ajaxComplete/

于 2012-08-15T15:44:32.030 回答