我如何让一个函数等待,直到所有的jQuery Ajax请求在另一个函数内完成?

简而言之,在执行下一个Ajax请求之前,我需要等待所有Ajax请求都完成。但如何?


当前回答

如果从头开始,我强烈建议使用$.when()。

尽管这个问题有超过一百万个答案,但我仍然没有找到任何对我的情况有用的答案。假设您必须处理现有的代码库,已经进行了一些ajax调用,并且不想引入承诺的复杂性和/或重做整个事情。

我们可以很容易地利用jQuery的.data, .on和.trigger函数,这些函数一直是jQuery的一部分。

Codepen

我的解决方案的优点是:

显然回调依赖于什么 函数triggerNowOrOnLoaded并不关心数据是否已经加载或我们仍在等待它 将其插入现有代码非常容易

$(function() { // wait for posts to be loaded triggerNowOrOnLoaded("posts", function() { var $body = $("body"); var posts = $body.data("posts"); $body.append("<div>Posts: " + posts.length + "</div>"); }); // some ajax requests $.getJSON("https://jsonplaceholder.typicode.com/posts", function(data) { $("body").data("posts", data).trigger("posts"); }); // doesn't matter if the `triggerNowOrOnLoaded` is called after or before the actual requests $.getJSON("https://jsonplaceholder.typicode.com/users", function(data) { $("body").data("users", data).trigger("users"); }); // wait for both types triggerNowOrOnLoaded(["posts", "users"], function() { var $body = $("body"); var posts = $body.data("posts"); var users = $body.data("users"); $body.append("<div>Posts: " + posts.length + " and Users: " + users.length + "</div>"); }); // works even if everything has already loaded! setTimeout(function() { // triggers immediately since users have been already loaded triggerNowOrOnLoaded("users", function() { var $body = $("body"); var users = $body.data("users"); $body.append("<div>Delayed Users: " + users.length + "</div>"); }); }, 2000); // 2 seconds }); // helper function function triggerNowOrOnLoaded(types, callback) { types = $.isArray(types) ? types : [types]; var $body = $("body"); var waitForTypes = []; $.each(types, function(i, type) { if (typeof $body.data(type) === 'undefined') { waitForTypes.push(type); } }); var isDataReady = waitForTypes.length === 0; if (isDataReady) { callback(); return; } // wait for the last type and run this function again for the rest of the types var waitFor = waitForTypes.pop(); $body.on(waitFor, function() { // remove event handler - we only want the stuff triggered once $body.off(waitFor); triggerNowOrOnLoaded(waitForTypes, callback); }); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body>Hi!</body>

其他回答

正如其他答案所提到的,你可以使用ajaxStop()等待直到所有ajax请求完成。

$(document).ajaxStop(function() {
     // This function will be triggered every time any ajax request is requested and completed
});

如果你想为特定的ajax()请求做这件事,你能做的最好的是在特定的ajax请求中使用complete()方法:

$.ajax({
    type: "POST",
    url: "someUrl",
    success: function(data) {
        // This function will be triggered when ajax returns a 200 status code (success)
    },
    complete: function() {
        // This function will be triggered always, when ajax request is completed, even it fails/returns other status code
    },
    error: function() {
        // This will be triggered when ajax request fail.
    }
});

但是,如果你只需要等待几个和特定的ajax请求被完成?使用美妙的javascript承诺等待,直到这些ajax你想等待完成。我做了一个简单易读的示例,向您展示promises如何与ajax一起工作。请看下一个例子。我使用setTimeout来阐明这个示例。

// Note: // resolve() is used to mark the promise as resolved // reject() is used to mark the promise as rejected $(document).ready(function() { $("button").on("click", function() { var ajax1 = new Promise((resolve, reject) => { $.ajax({ type: "GET", url: "https://miro.medium.com/max/1200/0*UEtwA2ask7vQYW06.png", xhrFields: { responseType: 'blob'}, success: function(data) { setTimeout(function() { $('#image1').attr("src", window.URL.createObjectURL(data)); resolve(" Promise ajax1 resolved"); }, 1000); }, error: function() { reject(" Promise ajax1 rejected"); }, }); }); var ajax2 = new Promise((resolve, reject) => { $.ajax({ type: "GET", url: "https://cdn1.iconfinder.com/data/icons/social-media-vol-1-1/24/_github-512.png", xhrFields: { responseType: 'blob' }, success: function(data) { setTimeout(function() { $('#image2').attr("src", window.URL.createObjectURL(data)); resolve(" Promise ajax2 resolved"); }, 1500); }, error: function() { reject(" Promise ajax2 rejected"); }, }); }); var ajax3 = new Promise((resolve, reject) => { $.ajax({ type: "GET", url: "https://miro.medium.com/max/632/1*LUfpOf7teWvPdIPTBmYciA.png", xhrFields: { responseType: 'blob' }, success: function(data) { setTimeout(function() { $('#image3').attr("src", window.URL.createObjectURL(data)); resolve(" Promise ajax3 resolved"); }, 2000); }, error: function() { reject(" Promise ajax3 rejected"); }, }); }); Promise.all([ajax1, ajax2, ajax3]).then(values => { console.log("We waited until ajax ended: " + values); console.log("My few ajax ended, lets do some things!!") }, reason => { console.log("Promises failed: " + reason); }); // Or if you want wait for them individually do it like this // ajax1.then(values => { // console.log("Promise 1 resolved: " + values) // }, reason => { // console.log("Promise 1 failed: " + reason) // }); }); }); img { max-width: 200px; max-height: 100px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button>Make AJAX request</button> <div id="newContent"> <img id="image1" src=""> <img id="image2" src=""> <img id="image3" src=""> </div>

试试这个方法。在Java脚本函数中进行循环以等待ajax调用完成。

function getLabelById(id)
{
    var label = '';
    var done = false;
    $.ajax({
       cache: false,
       url: "YourMvcActionUrl",
       type: "GET",
       dataType: "json",
       async: false,
       error: function (result) {
         label='undefined';
         done = true;
        },
       success: function (result) {
            label = result.Message;
            done = true;
        }
     });

   //A loop to check done if ajax call is done.
   while (!done)
   {
      setTimeout(function(){ },500); // take a sleep.
   }

    return label;
}

使用ajaxStop事件。

例如,假设你有一个载入…消息,同时获取100个ajax请求,你想隐藏该消息一旦加载。

jQuery文档:

$("#loading").ajaxStop(function() {
  $(this).hide();
});

请注意,它将等待所有ajax请求在该页面上完成。

当所有ajax加载完成时,我使用大小检查

function get_ajax(link, data, callback) { $.ajax({ url: link, type: "GET", data: data, dataType: "json", success: function (data, status, jqXHR) { callback(jqXHR.status, data) }, error: function (jqXHR, status, err) { callback(jqXHR.status, jqXHR); }, complete: function (jqXHR, status) { } }) } function run_list_ajax(callback){ var size=0; var max= 10; for (let index = 0; index < max; index++) { var link = 'http://api.jquery.com/ajaxStop/'; var data={i:index} get_ajax(link,data,function(status, data){ console.log(index) if(size>max-2){ callback('done') } size++ }) } } run_list_ajax(function(info){ console.log(info) }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>

这对我很有用 非常简单

return $.ajax({
  type: 'POST',
  url: urlBaseUrl
  data: {someData:someData},
  dataType: "json",
  success: function(resultData) { 
  }
});