首先要明白什么是 AJAX ?
AJAX = 異步 JavaScript 和 XML,
AJAX 是一種用于創建快速動態網頁的技術,
通過在后臺與服務器進行少量資料交換,AJAX 可以使網頁實作異步更新,這意味著可以在不重新加載整個網頁的情況下,對網頁的某部分進行更新,
傳統的網頁(不使用 AJAX)如果需要更新內容,必需多載整個網頁面,
有很多使用 AJAX 的應用程式案例:新浪微博、Google 地圖、開心網等等,
1、AJAX - 創建 XMLHttpRequest 物件
XMLHttpRequest 物件
所有現代瀏覽器都支持 XMLHttpRequest 物件 (IE5 和IE6 使用AcActiveXObject),
XMLHttpRequest 用于在后臺與服務器交換資料,這意味著可以在不重新加載整個網頁的情況下,對網頁的某部分進行更新,
所有現代瀏覽器(IE7+、Firefox、Chrome、Safari 以及 Opera)均內建 XMLHttpRequest 物件,
創建 XMLHttpRequest 物件的語法:
variable = new XMLHttpRequest();
老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 物件:
variable=new ActiveXObject( "Microsoft.XMLHTTP" );
為了應對所有的現代瀏覽器,包括 IE5 和 IE6,請檢查瀏覽器是否支持 XMLHttpRequest 物件,如果支持,則創建 XMLHttpRequest 物件,如果不支持,則創建 ActiveXObject :
1.1 XHR創建物件:
var xmlhttp; if ( window.XMLHttpRequest ) {// code for IE7+, Firefox, Chrom, Safari, Opera xmlhttp = new XMLHttpRequest(); } else {// code for IE5, IE6 xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" ); }
1.2、AJAX - 向服務器發送請求
XMLHttpRequest 物件用于和服務器交換資料,
向服務器發送請求
如需將請求發送到服務器,我們使用 XMLHttpRequest 物件的 open() 和 send() 方法:
xmlhttp.open("GET","test1.txt",true); //規定請求的型別、URL 以及是否異步處理請求, xmlhttp.send(); //將請求發送到服務器,
| 方法 | 描述 |
|---|---|
| open(method,url,async) |
規定請求的型別、URL 以及是否異步處理請求,
|
| send(string) |
將請求發送到服務器,
|
GET 還是 POST?
與 POST 相比,GET 更簡單也更快,并且在大部分情況下都能用,
然而,在以下情況中,請使用 POST 請求:
- 無法使用快取檔案(更新服務器上的檔案或資料庫)
- 向服務器發送大量資料(POST 沒有資料量限制)
- 發送包含未知字符的用戶輸入時,POST 比 GET 更穩定也更可靠
GET 請求
一個簡單的 GET 請求:
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
在上面的例子中,您可能得到的是快取的結果,
------解決方案--------------------
ajax請求 如果兩次請求地址一樣 服務器只會處理第一次請求
第二次請求回傳內容和第一次一樣
加 Math.random() 使每次請求地址不相同 服務器每次都去做不同的回應
------解決方案--------------------
Math.random()是呼叫javascript語法中的數學函式,能夠產生亂數,
在Ajax請求中作為URL引數傳遞,能夠有效的避免“ajax快取”
在IE 6系列的瀏覽器中,默認提交給一個地址例如:aa.aspx ,將自動快取,第二次再請求aa.aspx時候,就不會再重復請求了,當然,也可以使用new date () 時間戳的形式作為引數傳遞,
為了避免這種情況,請向 URL 添加一個唯一的 ID:
xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);
xmlhttp.send();
如果您希望通過 GET 方法發送資訊,請向 URL 添加資訊:
xmlhttp.open("GET","demo_get2.asp?fname=Bill&lname=Gates",true);
xmlhttp.send();
POST 請求
一個簡單 POST 請求:
xmlhttp.open("POST","demo_post.asp",true);
xmlhttp.send();
如果需要像 HTML 表單那樣 POST 資料,請使用 setRequestHeader() 來添加 HTTP 頭,然后在 send() 方法中規定您希望發送的資料:
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //向請求中添加 TTTP 頭;
xmlhttp.send("fname=Bill&lname=Gates");
| 方法 | 描述 |
|---|---|
| setRequestHeader(header,value) |
向請求添加 HTTP 頭,
|
url - 服務器上的檔案
open() 方法的 url 引數是服務器上檔案的地址:
xmlhttp.open("GET","ajax_test.asp",true);
該檔案可以是任何型別的檔案,比如 .txt 和 .xml,或者服務器腳本檔案,比如 .asp 和 .php (在傳回回應之前,能夠在服務器上執行任務),
異步 - True 或 False?
AJAX 指的是異步 JavaScript 和 XML(Asynchronous JavaScript and XML),
XMLHttpRequest 物件如果要用于 AJAX 的話,其 open() 方法的 async 引數必須設定為 true:
xmlhttp.open("GET","ajax_test.asp",true);
對于 web 開發人員來說,發送異步請求是一個巨大的進步,很多在服務器執行的任務都相當費時,AJAX 出現之前,這可能會引起應用程式掛起或停止,
通過 AJAX,JavaScript 無需等待服務器的回應,而是:
- 在等待服務器回應時執行其他腳本
- 當回應就緒后對回應進行處理
Async = true
當使用 async=true 時,請規定在回應處于 onreadystatechange 事件中的就緒狀態時執行的函式:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) // 請求完成并成功回傳
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
Async = false
如需使用 async=false,請將 open() 方法中的第三個引數改為 false:
xmlhttp.open("GET","test1.txt",false);
我們不推薦使用 async=false,但是對于一些小型的請求,也是可以的,
請記住,JavaScript 會等到服務器回應就緒才繼續執行,如果服務器繁忙或緩慢,應用程式會掛起或停止,
注釋:當您使用 async=false 時,請不要撰寫 onreadystatechange 函式 - 把代碼放到 send() 陳述句后面即可:
xmlhttp.open("GET","test1.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
1.3 AJAX - 服務器回應
如需獲得來自服務器的回應,請使用 XMLHttpRequest 物件的 responseText 或 responseXML 屬性,
| 屬性 | 描述 |
|---|---|
| responseText | 獲得字串形式的回應資料, |
| responseXML | 獲得 XML 形式的回應資料, |
responseText 屬性
如果來自服務器的回應并非 XML,請使用 responseText 屬性,
responseText 屬性回傳字串形式的回應,因此您可以這樣使用:
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
例:
<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>
responseXML 屬性
如果來自服務器的回應是 XML,而且需要作為 XML 物件進行決議,請使用 responseXML 屬性:
請求 books.xml 檔案,并決議回應:
xmlDoc=xmlhttp.responseXML; txt=""; x=xmlDoc.getElementsByTagName("ARTIST"); for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br />"; } document.getElementById("myDiv").innerHTML=txt;
例:
<html> <head> <script type="text/javascript"> function loadXMLDoc() { var xmlhttp; var txt,x,i; 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) { xmlDoc=xmlhttp.responseXML; txt=""; x=xmlDoc.getElementsByTagName("title"); for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br />"; } document.getElementById("myDiv").innerHTML=txt; } } xmlhttp.open("GET","/example/xmle/books.xml",true); xmlhttp.send(); } </script> </head> <body> <h2>My Book Collection:</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">獲得我的圖書收藏串列</button> </body> </html>
1.4 AJAX - onreadystatechange 事件
當請求被發送到服務器時,我們需要執行一些基于回應的任務,
每當 readyState 改變時,就會觸發 onreadystatechange 事件,
readyState 屬性存有 XMLHttpRequest 的狀態資訊,
下面是 XMLHttpRequest 物件的三個重要的屬性:
| 屬性 | 描述 |
|---|---|
| onreadystatechange | 存盤函式(或函式名),每當 readyState 屬性改變時,就會呼叫該函式, |
| readyState |
存有 XMLHttpRequest 的狀態,從 0 到 4 發生變化,
|
| status |
200: "OK" 404: 未找到頁面 |
在 onreadystatechange 事件中,我們規定當服務器回應已做好被處理的準備時所執行的任務,
當 readyState 等于 4 且狀態為 200 時,表示回應已就緒:
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }
例:
<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 的每個變化,
使用 Callback 函式
callback 函式是一種以引數形式傳遞給另一個函式的函式,
如果您的網站上存在多個 AJAX 任務,那么您應該為創建 XMLHttpRequest 物件撰寫一個標準的函式,并為每個 AJAX 任務呼叫該函式,
該函式呼叫應該包含 URL 以及發生 onreadystatechange 事件時執行的任務(每次呼叫可能不盡相同):
function myFunction() { loadXMLDoc("ajax_info.txt",function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }); }
例:
<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>
// code for IE7+, Firefox, Chrome, Opera, Safari
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/162714.html
標籤:JavaScript
