2012-10-31 77 views
0

問題:在Chrome中工作時,腳本未等待同步xhr響應。在FireFox/IE中正常工作。已經使用onreadyStateHandlers,但仍然在收到響應之前執行其他代碼。XHR同步調用在Chrome中失敗。不等待xhr響應的腳本

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; 

} 

請分享您的想法!

+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; 

} 
+0

謝謝Felix.Thanks的及時響應。所以無論我需要做什麼東西的迴應應該在callScript的回調函數的權利?這非常有用。非常感謝。 – Aki

+0

嗨,我正在執行$ http而不是xhr時遇到類似的情況。這次是爲所有$ http請求創建一個通用服務。 $ http服務被注入到所需的控制器。現在,當控制器調用$ http服務時,它不會等待響應並執行下一步。雖然在後端我可以發生$ http連接。所以總之如何$ http同步調用或帶回調函數。 – Aki