问题
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;
}
Please share your thoughts!!
回答1:
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;
}
来源:https://stackoverflow.com/questions/13152705/xhr-sync-calls-failing-in-chrome-script-not-waiting-for-the-xhr-response