2012-03-09 12 views
1

私はしばらくの間、JavaScriptを勉強していました。私がAJAXを学び始めたとき、私はこれまでに一度も見たことがないことを知りました。XMLHttpRequest()オブジェクトはどのようにこれを行いますか?

たとえば、このサンプルコードを参考にしてください。この関数が呼び出されると、ブラウザがhandleSayHello()を複数回呼び出すために続けて同じよう

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

は、それはです。何がブラウザでこれを行うのですか?以前は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で、2回目は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


を呼び出すされ、変更されたとき、あなたが何を要求するたびに、新しいXHRインスタンス
が必要ですか? – tkone

+0

'sayHello'はどこで呼び出されますか?ループしているように見えるので、 'setInterval(sayHello、...)'のような一定の間隔で呼び出されるように設定されています。 –

+0

私は間違いをして質問を編集したと思います。 sayHay()ではなく、複数回呼び出されているのはhandleSayHello()です。 –

答えて

3

次のコード行は、あなたのhandleSayHello機能にonreadystatechangeイベントをフックされています。 onreadystatechangeは、XMLHttpRequestrequestのライフサイクル中に何度も起動されるため、ハンドル関数は複数回実行されています。

receiveReq.onreadystatechange = handleSayHello; 

このarticleはreadyStateの値や変化にに関してかなり有益です。

+0

これによりhandleSayHello()が複数回呼び出されますか? –

+0

はいそうです.____ – zzzzBov

+0

はい、特にそのコード行です。準備完了状態が変化し、5つの可能な準備状態があるときはいつでも、オンデシステート変更がトリガされる。 – rwilliams

0

XHRのreadyStateのは、onreadystatechangeにイベントリスナーが `handleSayHello`が欠けているように見えるので、

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 () { 

} 
関連する問題