0

问题:在 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;

 }

请分享你的想法!!

4

1 回答 1

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;

 }
于 2012-10-31T07:13:45.317 回答