2012-03-09 7 views
1

나는 잠시 동안 JavaScript를 공부 해왔고 AJAX를 배우기 시작했을 때 나는 궁금한 적이 없었던 것을 보았다.XMLHttpRequest() 객체는 어떻게이 작업을 수행합니까?

예를 들어이 샘플 코드를 예로 들어 보겠습니다.

var receiveReq = XMLHttpRequest();  
//Initiate the asyncronous request. 
function sayHello() { 
    //If our XMLHttpRequest object is not in the middle of a request, start the new asyncronous call. 
    if (receiveReq.readyState == 4 || receiveReq.readyState == 0) { 
     //Setup the connection as a GET call to SayHello.html. 
     //True explicity sets the request to asyncronous (default). 
     receiveReq.open("GET", 'SayHello.html', true); 
     //Set the function that will be called when the XMLHttpRequest objects state changes. 
     receiveReq.onreadystatechange = handleSayHello; 
     //Make the actual request. 
     receiveReq.send(null); 
    }   
} 

function handleSayHello() { 
    //Check to see if the XmlHttpRequests state is finished. 
    if (receiveReq.readyState == 4) { 
     //Set the contents of our span element to the result of the asyncronous call. 
     document.getElementById('span_result').innerHTML = receiveReq.responseText; 
    }   
} 

이 함수를 호출하면 브라우저에서 handleSayHello()를 여러 번 계속 호출하는 것과 같습니다. 브라우저가 원인이되는 이유는 무엇입니까? 이전에는 JavaScript 나 다른 언어에서는 본 적이 없으며 나에게 의미가 없습니다. 어떻게 작동합니까? JavaScript와 같은 다른 것들이 있습니까?

또한 sayHello()의 if 문이 실행될 때 receiveReq.readyState이 0 또는 4가 아니면 어떻게됩니까?

편집 :

나는 기능 sayHello()에 작은 변화를 만들어 지금은 다음과 같습니다.

function sayHello() { 
    //If our XmlHttpRequest object is not in the middle of a request, start the new asyncronous call. 
    if (receiveReq.readyState == 4) { 
     //Setup the connection as a GET call to SayHello.html. 
     //True explicity sets the request to asyncronous (default). 
     receiveReq.open("GET", 'SayHello.html', true); 
     //Set the function that will be called when the XmlHttpRequest objects state changes. 
     receiveReq.onreadystatechange = handleSayHello; 
     //Make the actual request. 
     receiveReq.send(null); 
    }  
    else 
     alert("readyState = " + receiveReq.readyState);  
} 

코드는 여전히 작동합니다! 내가 찾은 것은이 if 문이 한 번 실행된다는 것이다. 처음에는 readyState = 0이고 두 번째 시간은 readyState = 4 일 때입니다. 어떻게 된 일입니까?

다음은 완전한 소스 코드입니다.

<html> 
    <head> 
     <title>The Hello World of AJAX</title> 
     <script language="JavaScript" type="text/javascript"> 
      //Gets the browser specific XMLHttpRequest Object 
      function getXmlHttpRequestObject() { 
       if (window.XMLHttpRequest) { 
        return new XMLHttpRequest(); //Not IE 
       } else if(window.ActiveXObject) { 
        return new ActiveXObject("Microsoft.XMLHTTP"); //IE 
       } else { 
        //Display your error message here. 
        //and inform the user they might want to upgrade 
        //their browser. 
        alert("Your browser doesn't support the XmlHttpRequest object. Better upgrade to Firefox."); 
       } 
      }   
      //Get our browser specific XMLHttpRequest object. 
      var receiveReq = getXmlHttpRequestObject();  
      //Initiate the asyncronous request. 
      function sayHello() { 
       //If our XMLHttpRequest object is not in the middle of a request, start the new asyncronous call. 
       if (receiveReq.readyState == 4 || receiveReq.readyState == 0) { 
        //Setup the connection as a GET call to SayHello.html. 
        //True explicity sets the request to asyncronous (default). 
        receiveReq.open("GET", 'SayHello.html', true); 
        //Set the function that will be called when the XMLHttpRequest objects state changes. 
        receiveReq.onreadystatechange = handleSayHello; 
        //Make the actual request. 
        receiveReq.send(null); 
       }   
      } 
      //Called every time our XMLHttpRequest objects state changes. 
      function handleSayHello() { 
       //Check to see if the XMLHttpRequest's state is finished. 
       if (receiveReq.readyState == 4) { 
        //Set the contents of our span element to the result of the asyncronous call. 
        document.getElementById('span_result').innerHTML = receiveReq.responseText; 
       } 
      } 
      </script> 
    </head> 
    <body> 
     <!-- Clicking this link initiates the asyncronous request --> 
     <a href="javascript:sayHello();">Say Hello</a><br /> 
     <!-- used to display the results of the asynchronous request --> 
     <span id="span_result"></span> 
    </body> 
</html> 

SayHello.html의 내용은 단지

hello, world 
+0

'handleSayHello'는없는 것 같다? – tkone

+0

sayHello는 어디에서 호출 되었습니까? 반복되는 것처럼 보이기 때문에, 주어진 간격 - setInterval (sayHello, ...)'에서 호출하도록 설정 될 수 있습니다. –

+0

실수를해서 내 질문을 편집 한 것 같습니다. handleSayHello()는 sayHello()가 아니라 여러 번 호출되는 것 같습니다. –

답변

3

다음의 코드는 onreadystatechange 이벤트를 후킹 당신의 handleSayHello 기능입니다. onreadystatechange은 XMLHttpRequestrequest의 수명주기 동안 여러 번 발생하므로 핸들 함수가 두 번 이상 실행됩니다. 안부 가치와 변화를 readyState가하기로

receiveReq.onreadystatechange = handleSayHello; 

article은 매우 유익하다.

+0

이로 인해 handleSayHello()가 여러 번 호출됩니까? –

+0

예 그렇습니다 .____ – zzzzBov

+0

예, 특히 해당 코드 줄. 설정 상태가 변경되고 5 가지 준비 상태가있을 때마다 onreadystate 변경이 트리거됩니다. – rwilliams

0

당신이 무엇을 요구, 새로운 XHR 인스턴스를 필요로 할 때마다 XHR의 readyState가 변경 될 때
이 ,을 onreadystatechange 이벤트 리스너가
를 호출합니다 그래서

function sayHello() { 
    var receiveReq = new XMLHttpRequest();  
    receiveReq.open("GET", 'SayHello.html', true); 
    receiveReq.onreadystatechange = function () { 
     if (receiveReq.readyState == 4) { 
     //do sth. 
      handleSayHello() 
     } 
    }; 
    receiveReq.send(null); 
} 
function handleSayHello () { 

} 
관련 문제