2012-10-11 127 views
1

所以我剛寫完我的第一個Ajax函數。我通過谷歌教程和w3schools完成了這一切,並且終於有效。唯一的問題是我沒有完全理解正在發生的事情的邏輯,並且正在尋找解釋!需要幫助瞭解Ajax功能

這裏是我完整的代碼

function loadPlayer(id) 
{ 
    var xmlhttp; 

    if (window.XMLHttpRequest) 
     xmlhttp=new XMLHttpRequest(); 
    else if(window.ActiveXObject) 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 

    xmlhttp.onreadystatechange=function() 
    { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
      document.getElementById("newPlayer").innerHTML=xmlhttp.responseText; 
    }; 

    xmlhttp.open("GET","http://localhost:8084/gmustudent/players?id=" + id,true); 
    xmlhttp.send(); 
} 

我的主要問題是關於我寫了這個代碼,因爲它涉及到每個語句的順序。我很困惑,因爲在onreadystatechange函數中,我抓取響應文本並將其放入newPlayer div中。然而,直到這個聲明之後,我才真正從網址異步獲取數據。

所以我很困惑,因爲我不明白如何將響應文本放在div中,如果你還沒有得到它。我看到它的工作原理,我只是不明白爲什麼。所以如果任何人都可以用簡單的術語來解釋這裏發生的事情,我會非常感激。尤其是因爲它涉及到我正在寫我的陳述的順序以及每個陳述實際上在做什麼。非常感謝!

回答

1

這樣的:

xmlhttp.onreadystatechange=function() 
    { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
      document.getElementById("newPlayer").innerHTML=xmlhttp.responseText; 
    }; 

是事件處理程序,這意味着,當事件被觸發它得到執行。在這種情況下,當你改變請求的狀態時。通過代碼的實際流量:

  1. 您附上事件處理程序在上面的代碼中
  2. 你讓實際的請求
  3. 這一事件onreadystatechange被反覆觸發的請求被處理(如狀態更改)
  4. 當請求準備就緒並且確定(即if塊)時,它將響應文本添加到div。

所以,你可以看到你在#1中附加了事件回調,然後你關心的代碼終於在#4被執行了。

+0

當你說「你提出實際要求」是這部分? xmlhttp.open(「GET」,「http:// localhost:8084/gmustudent/players?id =」+ id,true); – gmustudent

+0

是的,那開始的事件處理程序附加到它的請求 –

+0

現在我明白了!謝謝你,先生! – gmustudent

0

當您將功能XHR對象的.onreadystatechange屬性,你分配這樣一個所謂的回調函數。由於該名稱已告訴我們,該函數稍後將從另一個進程或應用程序的另一部分調用。

在這種情況下,它在幾個Ajax事件上被調用。例如,如果請求將要建立,數據是否被接收以及整個請求何時結束。這就是爲什麼你檢查那裏,如果readyState等於4和狀態200.

因此,代碼的順序並不重要,函數不立即執行,它只是被引用和稍後調用。

0

我在代碼中添加了一些關於各部分發生了什麼的註釋。

function loadPlayer(id) 
{ 
    var xmlhttp; 

    // This if/else block is trying to get the best request object for you, based on browser(ish). 
    if (window.XMLHttpRequest) 
     xmlhttp=new XMLHttpRequest(); 
    else if(window.ActiveXObject) 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 

    // This is declaring a function to run when the state changes on the ajax request. Note that just because you're creating the function here, does not mean it is running yet. It will only run when the ajax request triggers it. 
    xmlhttp.onreadystatechange=function() 
    { 
     // This is checking to see if it is finished. If it isn't finished, you don't have responseText to use. 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
      // Now that the request is actually back, we can take the text from the response and use it. 
      document.getElementById("newPlayer").innerHTML=xmlhttp.responseText; 
    }; 

    xmlhttp.open("GET","http://localhost:8084/gmustudent/players?id=" + id,true); 
    // Okay, now we're running the request. 
    xmlhttp.send(); 
} 

如果你願意,你可以看到你所做的功能的onreadystatechange過得去只是放置一個console.log(xmlhttp.readyState);聲明函數的第一線,在if塊以上調用。