ajax - 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_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 是如何工作的
希望能帮助到你
推荐阅读
- android - 无法从圆角矩形按钮中删除背景
- javascript - Jquery 像 Angular5 中的 DOM 选择
- c# - 使用 where 子句从数据表中获取值到数据表中
- excel - 无法在 MS-Excel Office365 的脚本实验室中创建片段和查看示例
- rabbitmq - 绑定密钥或路由密钥
- c# - AWS localstack SNS 端点到 localhost
- reactjs - 如何在模态中打开模态而不关闭父模态 | 反应模式
- javascript - JS使用lodash根据对象值对高级对象数组进行排序
- angular - 无法读取“未定义”反应形式 Angular 5 的属性,下拉列表中填充了远程数据
- docker - 如何在docker中访问etcd