Javascript Chrome中的XHR同步调用失败。脚本未等待xhr响应

Javascript Chrome中的XHR同步调用失败。脚本未等待xhr响应,javascript,xmlhttprequest,Javascript,Xmlhttprequest,问题:在Chrome中工作时,脚本未等待同步xhr响应。在FireFox/IE中工作正常。我们也使用了OnReadyStateHandler,但在收到响应之前,其他代码仍会执行 function callingScript() { var a=callServer(); alert(a);//Here a is showing undefined while executing in chrome. But in FF/IE its waiting for the

问题:在Chrome中工作时,脚本未等待同步xhr响应。在FireFox/IE中工作正常。我们也使用了OnReadyStateHandler,但在收到响应之前,其他代码仍会执行

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()不会等待请求响应。使用回调解决此问题:

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;

 }

请注意:说你的问题很紧急并不能帮助你得到答案,事实上可能会使人们拒绝帮助你。谢谢Felix。谢谢你的及时回复。因此,我需要对响应执行的任何操作都应该在callingScript的回调函数中,对吗?这非常有用。非常感谢。嗨,我在实现$http而不是xhr时遇到了类似的情况。这次我将为所有$http请求创建一个公共服务$http服务被注入到所需的控制器。现在,当控制器调用$http服务时,它不会等待响应并执行下一步。虽然在后端,我可以控制$http连接的发生。简而言之,如何使用同步调用或回调函数来$http。