2012-03-20 139 views
0

我已經在像COBOL strucutured編程和努力學習AJAX現在。新建AJAX,需要一些澄清

我看到這一段代碼在W3Schools的,並有以下幾個問題?

問題: 1. xmlhttp.onreadystatechange = function()函數將如何評估。是不是xmlhttp.open()和xmlhttp.send()需要在返回評估之前執行?

<html> 
<head> 
<script type="text/javascript"> 
function loadXMLDoc() 
{ 
var xmlhttp; 
if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    } 
else 
    {// code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
xmlhttp.onreadystatechange=function() 
    { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText; 
    } 
    } 
xmlhttp.open("GET","ajax_info.txt",true); 
xmlhttp.send(); 
} 
</script> 
</head> 
<body> 

<div id="myDiv"><h2>Let AJAX change this text</h2></div> 
<button type="button" onclick="loadXMLDoc()">Change Content</button> 

</body> 
</html> 
+0

我強烈建議你使用jQuery,即使你不熟悉它,至少其ajaxing輕鬆。 – Ashraf 2012-03-20 15:46:39

回答

0

JAX是異步

一旦你調用send(),瀏覽器會發送後臺請求。

當服務器回覆時,瀏覽器將調用onreadystatechange處理程序;這發生在你的其他代碼運行一段時間後。

+0

那麼,當服務器響應延遲時,它會等到響應被髮送了嗎? – user1050619 2012-03-20 16:10:50

+0

@ user1050619:否;什麼都沒有等。直到晚些時候它纔會調用回調。 – SLaks 2012-03-20 16:32:51