XMLHttpRequest 對象用于和服務(wù)器交換數據。
如需將請求發(fā)送到服務(wù)器,我們使用 XMLHttpRequest 對象的 open() 和 send() 方法:
xmlhttp.open("GET","test1.txt",true);xmlhttp.send();| 方法 | 描述 |
|---|---|
| open(method,url,async) | 規定請求的類(lèi)型、URL 以及是否異步處理請求。
|
| send(string) | 將請求發(fā)送到服務(wù)器。
|
與 POST 相比,GET 更簡(jiǎn)單也更快,并且在大部分情況下都能用。
然而,在以下情況中,請使用 POST 請求:
一個(gè)簡(jiǎn)單的 GET 請求:
xmlhttp.open("GET","demo_get.asp",true);xmlhttp.send();在上面的例子中,您可能得到的是緩存的結果。
為了避免這種情況,請向 URL 添加一個(gè)唯一的 ID:
xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);xmlhttp.send();如果您希望通過(guò) GET 方法發(fā)送信息,請向 URL 添加信息:
xmlhttp.open("GET","demo_get2.asp?fname=Bill&lname=Gates",true);xmlhttp.send();一個(gè)簡(jiǎn)單 POST 請求:
xmlhttp.open("POST","demo_post.asp",true);xmlhttp.send();如果需要像 HTML 表單那樣 POST 數據,請使用 setRequestHeader() 來(lái)添加 HTTP 頭。然后在 send() 方法中規定您希望發(fā)送的數據:
xmlhttp.open("POST","ajax_test.asp",true);xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlhttp.send("fname=Bill&lname=Gates");| 方法 | 描述 |
|---|---|
| setRequestHeader(header,value) | 向請求添加 HTTP 頭。
|
open() 方法的 url 參數是服務(wù)器上文件的地址:
xmlhttp.open("GET","ajax_test.asp",true);該文件可以是任何類(lèi)型的文件,比如 .txt 和 .xml,或者服務(wù)器腳本文件,比如 .asp 和 .php (在傳回響應之前,能夠在服務(wù)器上執行任務(wù))。
AJAX 指的是異步 JavaScript 和 XML(Asynchronous JavaScript and XML)。
XMLHttpRequest 對象如果要用于 AJAX 的話(huà),其 open() 方法的 async 參數必須設置為 true:
xmlhttp.open("GET","ajax_test.asp",true);對于 web 開(kāi)發(fā)人員來(lái)說(shuō),發(fā)送異步請求是一個(gè)巨大的進(jìn)步。很多在服務(wù)器執行的任務(wù)都相當費時(shí)。AJAX 出現之前,這可能會(huì )引起應用程序掛起或停止。
通過(guò) AJAX,JavaScript 無(wú)需等待服務(wù)器的響應,而是:
當使用 async=true 時(shí),請規定在響應處于 onreadystatechange 事件中的就緒狀態(tài)時(shí)執行的函數:
xmlhttp.onreadystatechange=function(){if (xmlhttp.readyState==4 && xmlhttp.status==200){document.getElementById("myDiv").innerHTML=xmlhttp.responseText;}}xmlhttp.open("GET","test1.txt",true);xmlhttp.send();您將在稍后的章節學(xué)習更多有關(guān) onreadystatechange 的內容。
如需使用 async=false,請將 open() 方法中的第三個(gè)參數改為 false:
xmlhttp.open("GET","test1.txt",false);我們不推薦使用 async=false,但是對于一些小型的請求,也是可以的。
請記住,JavaScript 會(huì )等到服務(wù)器響應就緒才繼續執行。如果服務(wù)器繁忙或緩慢,應用程序會(huì )掛起或停止。
注釋?zhuān)?/span>當您使用 async=false 時(shí),請不要編寫(xiě) onreadystatechange 函數 - 把代碼放到 send() 語(yǔ)句后面即可:
xmlhttp.open("GET","test1.txt",false);xmlhttp.send();document.getElementById("myDiv").innerHTML=xmlhttp.responseText;聯(lián)系客服