首页 > 解决方案 > Async XMLHttpRequest 在后面跟着代码重定向到 Firefox 和 Safari 中的另一个 URL 时不返回响应

问题描述

我在 FireFox 和 Safari 中的代码遇到问题,如下所示:

xhr = new window['XMLHttpRequest'];
xhr.onreadystatechange = function() {
if (done || xhr.readyState != 4) {
return;
}
done = true;
handleResponse(xhr.responseText, callback);
};
}
xhr.open('GET', uri+params, true);
xhr.withCredentials = true; 
xhr.send(null);

function handleResponse(responseText, callback) {
var error;
var result;
try {
result = toucan.JSON.parse(responseText)['result']; //connectedAuth 
logout result.
} catch (ex) {
result = undefined;
}
console.log("Result is" + result);

if (!result) {
var errorCode = 'UnknownError';
var errorMessage = 'An unknown error ocurred';
error = toucan.Base.format('%s: %s', errorCode, errorMessage);
}
invokeCallback(error, callback);

}

随后重定向为 :window.location.href = "index.php?module=login&method=logout";

但是,如果在 FireFox 中进行重定向,我不会从我提出的请求中得到任何响应。这在 Chrome 中可以正常工作,但在 Firefox 中则不行,并且特定于请求后跟重定向的情况。我无法控制要更改的重定向代码。有没有一种方法可以强制浏览器首先完成请求并在进行重定向之前获取响应,同时保持调用异步。

标签: ajax

解决方案


我建议您使用承诺,首先创建一个运行 ajax 调用的函数,该调用返回来自您的服务器的响应:

    ajax_AuthUser(id,pass){

      return   $.ajax({
        method: "POST",
        url: "authUser.php",
        data: { id: id, pass: pass}
      })

    }

其次使用 done 语句:

ajax_AuthUser(id,pass)
.done(function(response){
     //check the response here !! maybe  validate the json ?
      var auth = JSON.parse(response)
      if(auth.response == "approved"){
     //do something here
        }else{
     //do other stuff here
             }
          }).fail(function(response){
          //do something if fail
}).always(function(){
 //do something after the call finished
})

如果你想要一个活生生的例子,这里是一个jsfiddle,它展示了 Promise 是如何工作的

希望能帮助到你


推荐阅读