2011-06-23 17 views
23

從我在MDN閱讀參考,它說參數XMLHttpRequest的「真」。開()方法

If TRUE (the default), the execution of the JavaScript 
function will continue while the response of the server has not yet arrived. 
This is the A in AJAX. 

我一直在使用AJAX,但後來我有點迷茫的時候,我讀了。我認爲問題可能是我不清楚AJAX概念清楚..我知道當然AJAX不會刷新頁面,這意味着連接到服務器和響應完全在後臺完成。

但我可以想像根據該引用發生的事情是,如果我在我的JavaScript有這樣的代碼:

//true, therefore process the function while server retrieves url 
var xmlResponse; 
var url = "http://domain.com/file.xml"; 
xml_req.open("GET", url, true); 

xml_req.onreadystatechange = function() { 
    if(xml_req.readyState == 4 && xml_req.status == 200) { 
     if(xml_req.responseText != null) 
      xmlResponse = xml_req.responseXML; //server response may not yet arrive 
     else { 
      alert("failed"); 
      return false; 
     } 
    }; 
xml_req.send(null); 

難道這不是意味着xmlResponse可以在這個意義上是不確定的,服務器是仍然檢索數據?有人可以解釋一下AJAX技術的流程是什麼?提前致謝。

+0

您需要更多信息?更多問題? – epascarello

+0

@epascarello:謝謝我認爲我很清楚,thx的幫助。我無法接受兩個答案,但我會先與我回答的人一起 –

回答

20

我寫了更詳細的文章here,但這是基本的想法。

將其設置爲true表示您正在發出異步請求。這意味着代碼不會暫停,直到http請求完成。一個同步調用鎖定瀏覽器,所以沒有別的運行。這可能會導致問題,所以人們更喜歡異步。

XHR對象更新我們正在做的事情。它爲我們提供了onreadystatechange事件的更新。我們註冊了一個函數,以便我們可以跟蹤它的狀態。 onreadystatechange被調用4次。每一個不同的狀態

0 = uninitialized 
1 = loading 
2 = loaded 
3 = interactive 
4 = complete 

的數據是提供給我們當readyState爲4

現在你張貼,它正在檢查完成狀態的代碼,它可以確保狀態200 [確定]

if(xml_req.readyState == 4 && xml_req.status == 200){ 

,如果你嘗試在代碼中的其他地方使用它返回之前的xmlResponse的價值是不確定的。一個例子

ml_req.send(null); 
alert(xmlResponse); 

一個對XMLHttpRequest的文章中第一個文章的可能是你一個很好看的。 Apple Article on xmlhttpreq

+0

'onreadystatechange'處理程序可能被調用的次數多於或少於4次。對於分塊響應,可以使用'readyState === 3'多次調用處理程序:[jsfiddle.net/f067xas8](http://jsfiddle.net/f067xas8/) – gilly3

4

要了解的重要一點是,您的onreadystatechange處理程序不會立即執行。它不止一次執行。它可能會更容易概念化,如果你打破件爲三個獨立的功能:

function makeRequest(url) 
{ 
    var xhr = new XMLHttpRequest(); 
    xhr.open("GET", url, true); 
    xhr.onreadystatechange = receiveResponse; 
    xhr.send(); 
} 
function receiveResponse(e) 
{ 
    if (this.readyState == 4) 
    { 
     // xhr.readyState == 4, so we've received the complete server response 
     if (this.status == 200) 
     { 
      // xhr.status == 200, so the response is good 
      var response = this.responseXML; 
      ... 
     } 
    } 
} 

首先,makeRequest叫,然後退出。然後,只要我們從服務器收到任何迴應,就會調用receiveResponse。每次,我們都會檢查是否完全收到回覆,然後纔會繼續處理回覆。