ℙℕℤℝ 2012-10-03 11:49
浏览 82

jquery-ajax多次调用

I'm using the following code to have multiple ajax requests like this:

request 1 start | request 1 finish | request 2 start | request 2 finish | ...

This is the code:

var startingpoint = fireRequest(1);
    $.each(types,function(ix,type) 
    {
       startingpoint = startingpoint.pipe( function() 
       {
          alert(startingpoint.status); // undefined
          return fireRequest(type);
        });
    });

fireRequest is just a switchcase to the correct ajax function which returns $.ajax(...)

I'd like the chain to stop when one request fails. I started implementing it and as a test I'd like to alert the status of the ajax object, but it shows 'undefined'. How can I get the status?

  • 写回答

3条回答 默认 最新

  • weixin_33701564 2012-10-08 03:32
    关注

    JS example 1

    this code assumes you want to abort the other requests if any one request fails (via a 404 or 500 response, or times out) , and does not need to evaluate the data response to determine a business logic failure scenario. $.when()

    The method will resolve its master Deferred as soon as all the Deferreds resolve, or reject the master Deferred as soon as one of the Deferreds is rejected.

        $.when(fireRequest(1), fireRequest(2),fireRequest(3))
      .then(myAllSuccessfulFunc, oneFailedFunc);
    
    function myAllSuccesfulFunc(req1,req2,req3){
    //everything returned a 200.
       alert("these are not the droids you are looking for");
    };
    function oneFailedFunc(req1,req2,req3){
        //* each req looks like [ "not success", statusText, jqXHR ] */
    //feel free to check what failed, but I don't know what you need
    
       req1[2].abort();
       req2[2].abort();
       req3[2].abort();
    };
    

    js example 2

    you actually need to parse a successful request for data in the response to see if you should fail the other requests due to logic from the back end.

    var stop = 4;
    //if you are sure fireRequest(x) returns a good promise object, do this:
    callNext(fireRequest(1),1);
    
    function callNext(promise, currentIndex){
       promise.done(function(ajaxArgs){
       var jqXHR = ajaxArgs[2];
    //replace this with some logic check that makes sense to your app
       if(/error/.test(jqXHR.responseText)){
        //do something
       }else if(currentIndex <stop){
        callNext(fireRequest(currentIndex+1),currentIndex+1);
       }).fail(function(ajaxArgs){
       //server returned a 404, or a 500, or something not a success.
       });
    };
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)