2012-10-31 3 views
0

문제 : Chrome에서 작업하는 동안 스크립트는 동기식 xhr 응답을 기다리지 않습니다. FireFox/IE에서 잘 작동합니다. onreadyStateHandlers도 사용했지만 응답을 받기 전에 다른 코드가 실행됩니다.Chrome에서 XHR 동기화 호출에 실패했습니다. 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에게 감사드립니다. 신속한 답변을 부탁드립니다. 따라서 응답과 관련된 모든 것들이 callScript 함수의 콜백 함수 내에 있어야합니다. 그건 꽤 유용 했어. 고마워. – Aki

+0

안녕하세요, xhr 대신 $ http를 구현하는 동안 유사한 상황에 직면하고 있습니다. 이번에는 모든 $ http 요청에 대한 공통 서비스를 만들고 있습니다. $ HTTP 서비스가 필요한 컨트롤러에 주입됩니다. 이제 컨트롤러가 $ http 서비스를 호출하면 응답을 기다리지 않고 다음 단계를 실행합니다. 백엔드에서는 $ http 연결이 발생할 수 있지만. 그래서 짧은 방법으로 $ http 동기식 호출 또는 콜백 함수. – Aki