一、onreadystatechange 事件javascript
當請求被髮送到服務器時,咱們須要執行一些基於響應的任務。html
每當 readyState 改變時,就會觸發 onreadystatechange 事件。java
readyState 屬性存有 XMLHttpRequest 的狀態信息。ajax
屬性 | 描述 |
---|---|
onreadystatechange | 存儲函數(或函數名),每當 readyState 屬性改變時,就會調用該函數。 |
readyState | 存有 XMLHttpRequest 的狀態。從 0 到 4 發生變化。服務器
|
status | 200: "OK"函數 404: 未找到頁面網站 |
在 onreadystatechange 事件中,咱們規定當服務器響應已作好被處理的準備時所執行的任務。this
當 readyState 等於 4 且狀態爲 200 時,表示響應已就緒:url
<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/test1.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="loadXMLDoc()">經過 AJAX 改變內容</button> </body> </html>
註釋:onreadystatechange 事件被觸發 5 次(0 - 4),對應着 readyState 的每一個變化。spa
二、使用 Callback 函數
callback 函數是一種以參數形式傳遞給另外一個函數的函數。
若是您的網站上存在多個 AJAX 任務,那麼您應該爲建立 XMLHttpRequest 對象編寫一個標準的函數,併爲每一個 AJAX 任務調用該函數。
該函數調用應該包含 URL 以及發生 onreadystatechange 事件時執行的任務(每次調用可能不盡相同):
<html> <head> <script type="text/javascript"> var xmlhttp; function loadXMLDoc(url,cfunc) { 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=cfunc; xmlhttp.open("GET",url,true); xmlhttp.send(); } function myFunction() { loadXMLDoc("/ajax/test1.txt",function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="myFunction()">經過 AJAX 改變內容</button> </body> </html>