XHR sync calls failing in Chrome. Script not waiting for the xhr response

拥有回忆 提交于 2020-01-06 08:16:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!