send ajax request without waiting answer

2019-07-20 12:59发布

I want to make an ajax request to send some information and immediately after sending it (doesnt matter if I get an error/success) make a redirection (without waiting server response)

I was wondering if I do something like

$.ajax({
url:_myurl_,
timeout:500,
success:function(){document.location= _redirectUrl_},
error: function(){document.location= _redirectUrl_}
})

will work fine? Does adding a timeout wont cancel my request?

3条回答
smile是对你的礼貌
2楼-- · 2019-07-20 13:36

AJAX by definition is asynchronous. Just add location redirect code AFTER the ajax block, not Inside AJAX.

function dummyAjax(){
    $.ajax({
      //do something
      success:function(res){
          console.log(res);//chrome try preserve log you'll see this response even after redirection
      }
    });
    window.location.replace('https://google.com');//this would fire without waiting for ajax response
}
查看更多
【Aperson】
3楼-- · 2019-07-20 13:38

async: false in async Mode process are not wait to complete other process

查看更多
别忘想泡老子
4楼-- · 2019-07-20 13:43

Just do not implement any success handler.

So you could do ...

$.ajax({
    type: "post",
    url: "/log-message"
});

And since it is asynchronous, it will be non blocking and any code following this statement will be executing without waiting from the response from the server.

查看更多
登录 后发表回答