问题:在Chrome中工作时,脚本不等待同步xhr响应。在FireFox / IE中正常工作。已经使用过onreadyStateHandlers,但是在收到响应之前,仍会执行其他代码。
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;
}
请分享您的想法!!
答案 0 :(得分:1)
函数callServer()不等待响应请求。使用回调来解决这个问题:
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;
}