Ajax封装的请求需要等待累积的结果

ajax encapsulated request needs to wait for accumulated result

本文关键字:等待 结果 封装 请求 Ajax      更新时间:2023-09-26

我的web应用程序在ajax请求中的结构如下:

 $.ajax({
    type : "GET",
    url: '...',
    dataType: "xml",
    success: function(xml) {
                $.ajax({
                    type : "GET",
                    url : "....",
                    dataType : "xml",
                    success : function(xml) {
                    },
                    error : function(xhr) {
                        alert(xhr.responseText);
                    }
                });
                $.ajax({
                    type : "GET",
                    url : "....",
                    dataType : "xml",
                    success : function(xml) {
                    },
                    error : function(xhr) {
                        alert(xhr.responseText);
                    }
                });
                $.ajax({
                    type : "GET",
                    url : "...",
                    dataType : "xml",
                    success : function(xml) {
                    },
                    error : function(xhr) {
                        alert(xhr.responseText);
                    }
                });

        }
 });

我需要在我做其他事情之前完成这里正在做的所有请求。因为我需要他们加载内容到div.然后追加到html元素在我的代码。我不想使用(文档)。ajaxStop,因为这会破坏我的代码。

我怎样才能做到这一点?

你可以使用不同的($.Deferred)对象使你的代码看起来更干净,

每个$.ajax请求返回一个不同的对象,并将它们与$.when.done()组合使用,如下所示

$.when(req1, req2, req3).done(function (resp1, resp2, resp3) {
    //This will be executed on the success of all three requests
})

在你的情况下,你可以这样做

var req1 = $.ajax({type:"GET", url: "..."});
req1.done(function (resp1) {
    // This will execute after the first request is done
    var req2 = $.ajax({type:"GET", url: "..."}),
        req3 = $.ajax({type:"GET", url: "..."}),
        req4 = $.ajax({type:"GET", url: "..."});
    $.when(req2, req3, req4).done(function (resp2, resp3, resp4) {
        // when other three request are done
    });
    // If there are arbitrary number of requests, please consider the following
    var requestsArray = [],
        numberOfRequests = 10;
    for (var i=0; i<numberOfRequests; i++) {
        var request = $.ajax({type:"GET", url: "..."});
        requestsArray.push(request);
    };
    $.when.apply(null, requestsArray).done(function () {
        // You can collect the responses in the same order from `arguments`
        var responses = arguments;
    });
});

延迟对象提供了一种非常好的方式来处理回调,要了解更多关于延迟对象的信息,请查看http://api.jquery.com/category/deferred-object/

jQuery的$.ajax默认返回一个承诺($.Deferred)。你不需要使用回调你可以用这些承诺代替。然后使用$。当函数时,你可以创建一个新的承诺,它将等待这三个承诺完成,并执行所有你需要的操作。

看看链接页面底部的例子,看看它是如何工作的。

编辑:如果文档是正确的,那么它应该是这样的:

$.ajax({
  type : "GET",
  url: '...',
  dataType: "xml"
})
  .then(function (xml) {
    return $.when(
      $.ajax({
        type : "GET",
        url : "....",
        dataType : "xml"
      }),
      $.ajax({
        type : "GET",
        url : "....",
        dataType : "xml"
      }),
      $.ajax({
        type : "GET",
        url : "...",
        dataType : "xml"
      })
    );
  })
  .then(function (res1, res2, res3) {
    var xml1 = res1[0], xml2 = res2[0], xml3 = res3[0];

  });

但是我没有测试它,所以我不知道它是否真的正确。

我认为你可以使用Jquery buffer,就像这样。串行呼叫

  $.ajax('http://echo.jsontest.com/id/1')
  .then(function(result){
      console.log(JSON.stringify(result));
      return $.ajax('http://echo.jsontest.com/id/2')
  }).then(function(result){
      console.log(JSON.stringify(result));
      return $.ajax('http://echo.jsontest.com/id/3')
  }).then(function(result){
      console.log(JSON.stringify(result));
  });

Paralel叫

$.when(
     $.ajax('http://echo.jsontest.com/id/1'),
     $.ajax('http://echo.jsontest.com/id/2'),
     $.ajax('http://echo.jsontest.com/id/3')
 ).then(function(result1, result2, result3){
     console.log(JSON.stringify(result1[0]));
     console.log(JSON.stringify(result2[0]));
     console.log(JSON.stringify(result3[0]));
 })