【问题标题】:XHR sync calls failing in Chrome. Script not waiting for the xhr responseXHR 同步调用在 Chrome 中失败。脚本不等待 xhr 响应
【发布时间】:2012-10-31 06:53:13
【问题描述】:

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

 }

请分享你的想法!!

【问题讨论】:

  • 请注意:说您的问题很紧急并不能帮助您获得答案,实际上可能会让人们不再帮助您。

标签: javascript xmlhttprequest


【解决方案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;

 }

【讨论】:

  • 感谢 Felix。感谢您的及时回复。所以我需要对响应做的任何事情都应该在 callScript 的回调函数中,对吗?那非常有用。非常感谢。
  • 嗨,我在实现 $http 而不是 xhr 时遇到了类似的情况。这次我为所有 $http 请求创建了一个公共服务。 $http 服务被注入到所需的控制器中。现在当控制器调用 $http 服务时,它不会等待响应并执行下一步。虽然在后端我可以 c 发生 $http 连接。所以简而言之如何 $http 进行同步调用或使用回调函数。
猜你喜欢
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 2012-11-08
  • 1970-01-01
  • 2013-12-16
  • 1970-01-01
  • 2016-06-23
  • 2023-03-24
相关资源
最近更新 更多