XHR 同步调用在 Chrome 中失败.脚本不等待 xhr 响应 [英] XHR sync calls failing in Chrome. Script not waiting for the xhr response
本文介绍了XHR 同步调用在 Chrome 中失败.脚本不等待 xhr 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题:在 Chrome 中工作时,脚本没有等待同步 xhr 响应.在 FireFox/IE 中工作正常.也使用了 onreadyStateHandlers,但仍然在收到响应之前执行其他代码.
Issue: While working in Chrome, script not waiting for the Synchronous xhr response. Working fine in FireFox/IE. Have used onreadyStateHandlers as well, but still, before the response is received the other codes are executed.
function callingScript()
{ var a=callServer();
alert(a);//Here a is showing undefined while executing in chrome.
But in FF/IE its waiting for the response and then alerts a with response.
}
function callServer()
{
var response;
var httpRequest = new XMLHttpRequest();
httpRequest.open("POST","abc",false);
httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
httpRequest.onreadystatechange = function()
{
if (httpRequest.readyState != 4)
{return; }
if (httpRequest.status != 200)
{response=httpRequest.status;}
else {response=httpRequest.responseText;}
};
httpRequest.send(data);
return response;
}
请分享您的想法!!
推荐答案
函数 callServer() 不会等待请求得到响应.使用回调来解决这个问题:
the function callServer() does not wait for the request to be responded. use a callback to solve this problem:
function callingScript()
{ callServer(function(response) {
alert(response);
});
}
function callServer(callback)
{
var response;
var httpRequest = new XMLHttpRequest();
httpRequest.open("POST","abc",false);
httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
httpRequest.onreadystatechange = function()
{
if (httpRequest.readyState != 4)
{return; }
if (httpRequest.status != 200)
{response=httpRequest.status;}
else {response=httpRequest.responseText;}
callback(response);
};
httpRequest.send(data);
return response;
}
这篇关于XHR 同步调用在 Chrome 中失败.脚本不等待 xhr 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文