两个ajax调用,都重定向:一个请求可以失败吗?

时间:2017-03-22 18:31:50

标签: javascript jquery ajax

我有两个连续的ajax帖子请求,这两个请求在完成后将导航页面。

当然我应该在导航之前检查两个返回,但我很好奇:如下所示,设置是否真实地使其中一个请求失败?

失败我的意思是服务器不会接收/处理它。

function redirect(){
  window.location.href="./success";
}

//First call
$.ajax({
  type: "POST",
  url: url,
  data: data,
  complete:redirect
});
  
//Second call
$.ajax({
  type: "POST",
  url: url,
  data: data,
  complete:redirect
});

我的想法:T1,第一次ajax调用,T2,第二次ajax调用,T3,首先返回并重定向。

由于T3> T2,在重定向之前不会进行第二次调用吗?它不必返回成功。

3 个答案:

答案 0 :(得分:2)

Both requests will be made. Whichever one finishes first will cause the browser to cancel the second one. But as Kevin B pointed out, your server will most likely continue processing it and will be unaware that the client cancelled it (at least this is the way it works with apache) until the server tries to send something back to the client (and even then it's a crapshoot depending on your architecture).

It's very important to note the distinction between a failed request and a client cancelled request. In your case, the browser will cancel any ajax request that is ongoing when the page is unloading, but that doesn't mean the server won't process the instructions it received from the request.

答案 1 :(得分:0)

是的,ajax调用是异步的,所以回答你的问题

来自你的两个ajax请求,如果它在dom ready call上,哪个会先得到完整的响应会重定向你的页面并发送ajax最终会失败..

它会同时进行两次调用,但是一旦您的页面被重定向,您的成功回调将失败,在这种情况下,如果服务器参与第二页活动,它最终将失败。此外,如果服务器将发送成功回调,如果重定向只是客户端,服务器可能会成功运行。

答案 2 :(得分:0)

Yes one of the requests will probably fail as both requests are asynchronous and as soon as one of the requests get completed the page will be redirected thus cancelling the other request.

What you can do is define a variable and check for its value before redirecting.

    function redirect(){
      window.location.href="./success";
    }
   window.completed = 0; // if values is 2  that means both             requests are complete

//First call
$.ajax({
  type: "POST",
  url: url,
  data: data,
  complete:function(){
     window.complete++!
     if(window.complete == 2)
     {
          redirect();
     }
  }
});

//Second call
$.ajax({
  type: "POST",
  url: url,
  data: data,
  complete:function(){
     window.complete++!
     if(window.complete == 2)
     {
          redirect();
     }
  }
});