AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML)。 AJAX 不是新的編程語言,而是一種使用現有標準的新方法。 AJAX 是與服務器交換數據並更新部分網頁的藝術,在不從新加載整個頁面的狀況下。javascript
AJAX即「Asynchronous Javascript And XML」(異步JavaScript和XML),是指一種建立交互式網頁應用的網頁開發技術。php
AJAX = 異步 JavaScript和XML(標準通用標記語言的子集)。html
AJAX 是一種用於建立快速動態網頁的技術。java
經過在後臺與服務器進行少許數據交換,AJAX 可使網頁實現異步更新。這意味着能夠在不從新加載整個網頁的狀況下,對網頁的某部分進行更新。node
傳統的網頁(不使用 AJAX)若是須要更新內容,必須重載整個網頁頁面。jquery
Ajax 的核心是 JavaScript 對象 XMLHttpRequest。該對象在 Internet Explorer 5 中首次引入,它是一種支持異步請求的技術。簡而言之,XMLHttpRequest使您可使用 JavaScript 向服務器提出請求並處理響應,而不阻塞用戶。web
AJAX的優缺點:面試
優勢:ajax
不須要插件支持數據庫
用戶體驗極佳
提高Web程序性能
減輕服務器和寬帶的負擔
缺點:
前進後退按鈕被破壞
搜索引擎的支持不夠
開發調試工具缺少
AJAX 工做原理
AJAX是基於現有的Internet標準,而且聯合使用它們:
XMLHttpRequest 對象 (異步的與服務器交換數據)
JavaScript/DOM (信息顯示/交互)
CSS (給數據定義樣式)
XML (做爲轉換數據的格式)
AJAX應用程序與瀏覽器和平臺無關的!
相關網址:
AJAX官網:
http://api.jquery.com/category/ajax/
AJAX配置環境下載:
http://www.w3cschool.cn/jquerygroup/639a1r47.html
AJAX的工做原理至關於在用戶和服務器之間加了—箇中間層(AJAX引擎),使用戶操做與服務器響應異步化。
爲了幫助您理解 AJAX 的工做原理,咱們建立了一個小型的 AJAX 應用程序:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tryrun 1</title> </head> <body> <div id="view"> <p>點擊下面的按鈕,將 Ajax 請求回來的數據更新在該文本內</p> </div> <button type="button" id="btn">發起 Ajax 請求</button> <script> document.getElementById("btn").onclick = ajaxRequest; function ajaxRequest () { var xhr = new XMLHttpRequest(); xhr.open("GET", "https://www.w3cschool.cn/statics/demosource/ajax_info.txt", true); xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById("view").innerHTML = xhr.responseText; } } } </script> </body>
上面的 AJAX 應用程序包含一個 div 和一個按鈕。 div 部分用於顯示來自服務器的信息。當按鈕被點擊時,它負責調用名爲 loadXMLDoc() 的函數:
<!DOCTYPE html> <html> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>
接下來,在頁面的 head 部分添加一個 <script> 標籤。該標籤中包含了這個 loadXMLDoc() 函數:
<head> <script> function loadXMLDoc() { .... AJAX script goes here ... } </script> </head>
要建立AJAX實例,須要使用服務器端語言,例如Servlet,JSP,PHP,的ASP.Net等,這裏咱們使用JSP來講一下。
建立AJAX的實例步驟:
在嘗試AJAX示例時,沒有不連續性而且您能夠很是快速地得到響應,可是當您嘗試標準GCI示例時,您將不得不等待響應而且您的頁面也會獲得刷新。
XMLHttpRequest 是 AJAX 的基礎。
XMLHttpRequest 術語縮寫爲XHR,中文能夠解釋爲可擴展超文本傳輸請求。
XMLHttpRequest 對象能夠在不向服務器提交整個頁面的狀況下,實現局部更新網頁。
XMLHttpRequest的對象用於客戶端和服務器之間的異步通訊。
它執行如下操做:
全部現代瀏覽器均支持 XMLHttpRequest 對象(IE5 和 IE6 使用 ActiveXObject)。
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 ::
實例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tryrun 1</title> </head> <body> <div id="view"> <p>點擊下面的按鈕,將 Ajax 請求回來的數據更新在該文本內</p> </div> <button type="button" id="btn">發起 Ajax 請求</button> <script> document.getElementById("btn").onclick = ajaxRequest; function ajaxRequest () { var xhr = new XMLHttpRequest(); xhr.open("GET", "https://www.w3cschool.cn/statics/demosource/ajax_info.txt", true); xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById("view").innerHTML = xhr.responseText; } } } </script> </body>
XMLHttpRequest對象的常見屬性以下:
XMLHttpRequest對象的重要方法以下:
方法 | 描述 |
---|---|
abort() |
取消當前請求。 |
getAllResponseHeaders() |
以字符串形式返回完整的HTTP標頭集。 |
getResponseHeader( headerName ) |
返回指定HTTP標頭的值。 |
void open(method,URL) | 打開指定獲取或交的方法和URL的請求。 |
void open(method,URL,async) | 與上面相同,但指定異步或不。 |
void open(method,URL,async,userName,password) |
與上面相同,但指定用戶名和密碼。 |
void send(content) | 發送獲取請求。 |
setRequestHeader( label,value) |
將標籤/值對添加到要發送的HTTP標頭。 |
屬性 | 描述 |
---|---|
onreadystatechange |
存儲函數(或函數名),每當readyState的屬性改變時,就會調用該函數。 |
readyState | 存有的XMLHttpRequest的狀態從0到4發生變化。 0:請求未初始化 1:服務器鏈接已創建 2:請求已接收 3:請求處理中 4:請求已完成,且響應已就緒 |
reponseText | 以文本形式返回響應。 |
responseXML | 以XML格式返回響應 |
status |
將狀態返回爲數字(例如,「Not Found」爲404,「OK」爲200) |
statusText |
以字符串形式返回狀態(例如,「Not Found」或「OK」) |
AJAX使用的XMLHttpRequest的對象與服務器通訊。讓咱們嘗試經過下面顯示的圖像瞭解AJAX的流程或AJAX的工做原理。
正如您在上面的示例中所看到的,XMLHttpRequest對象起着重要做用。
XMLHttpRequest 對象用於和服務器交換數據。
當你的頁面所有加載完畢後,客戶端會經過 XMLHttpRequest 對象向服務器請求數據,服務器端接受數據並處理後,向客戶端反饋數據。
如需將請求發送到服務器,咱們使用 XMLHttpRequest 對象的open()
和send()
方法:
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
方法 | 描述 |
---|---|
open(method,url,async) | 規定請求的類型、URL 以及是否異步處理請求。
|
send(string) | 將請求發送到服務器。
|
與POST
相比,GET 更簡單也更快,而且在大部分狀況下都能用。
然而,在如下狀況中,請使用POST
請求:
沒法使用緩存文件(更新服務器上的文件或數據庫)
向服務器發送大量數據(POST
沒有數據量限制)
發送包含未知字符的用戶輸入時,POST
比GET
更穩定也更可靠
一個簡單的GET
請求:
實例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> 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","/statics/demosource/demo_get.php",true); xmlhttp.send(); } </script> </head> <body> <h2>AJAX</h2> <button type="button" onclick="loadXMLDoc()">Request data</button> <div id="myDiv"></div> </body> </html>
在上面的例子中,您可能獲得的是緩存的結果。
爲了不這種狀況,請向 URL 添加一個惟一的 ID:
xmlhttp.open("GET","demo_get.html?t=" + Math.random(),true);
xmlhttp.send();
若是您但願經過GET
方法發送信息,請向 URL 添加信息:
xmlhttp.open("GET","demo_get2.html?fname=Henry&lname=Ford",true); xmlhttp.send();
提示:GET
請求具備如下的幾個特色:
GET
請求可被緩存GET
請求保留在瀏覽器歷史記錄中GET
請求可被收藏爲書籤GET
請求不該在處理敏感數據時使用GET
請求有長度限制GET
請求只應當用於取回數據
一個簡單POST
請求:
實例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> 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("POST","/statics/demosource/demo_post.php",true); xmlhttp.send(); } </script> </head> <body> <h2>AJAX</h2> <button type="button" onclick="loadXMLDoc()">Request data</button> <div id="myDiv"></div> </body> </html>
若是須要像 HTML 表單那樣 POST 數據,請使用setRequestHeader()
來添加 HTTP 頭。而後在send()
方法中規定您但願發送的數據:
xmlhttp.open("POST","ajax_test.html",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("fname=Henry&lname=Ford");
方法 | 描述 |
---|---|
setRequestHeader(header,value) | 向請求添加 HTTP 頭。
|
提示:POST
請求的特色以下:
POST
請求不會被緩存POST
請求不會保留在瀏覽器歷史記錄中POST
請求不能被收藏爲書籤POST
請求對數據長度沒有要求open()
方法的url
參數是服務器上文件的地址:
xmlhttp.open("GET","ajax_test.html",true);
該文件能夠是任何類型的文件,好比.txt
和.xml
,或者服務器腳本文件,好比.asp
和.php
(在傳回響應以前,可以在服務器上執行任務)。
AJAX 指的是異步 JavaScript 和 XML(Asynchronous JavaScript and XML)。
XMLHttpRequest 對象若是要用於 AJAX 的話,其open()
方法的sync
參數必須設置爲 true:
xmlhttp.open("GET","ajax_test.html",true);
對於 web 開發人員來講,發送異步請求是一個巨大的進步。不少在服務器執行的任務都至關費時。AJAX 出現以前,這可能會引發應用程序掛起或中止。
經過 AJAX,JavaScript 無需等待服務器的響應,而是:
在等待服務器響應時執行其餘腳本
當響應就緒後對響應進行處理
當使用 async=true 時,請規定在響應處於 onreadystatechange 事件中的就緒狀態時執行的函數:
實例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tryrun 1</title> </head> <body> <div id="view"> <p>點擊下面的按鈕,將 Ajax 請求回來的數據更新在該文本內</p> </div> <button type="button" id="btn">發起 Ajax 請求</button> <script> document.getElementById("btn").onclick = ajaxRequest; function ajaxRequest () { var xhr = new XMLHttpRequest(); xhr.open("GET", "https://www.w3cschool.cn/statics/demosource/ajax_info.txt", true); xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById("view").innerHTML = xhr.responseText; } } } </script> </body>
如需使用 async=false,請將open()
方法中的第三個參數改成 false:
xmlhttp.open("GET","test1.txt",false);
咱們不推薦使用 async=false,可是對於一些小型的請求,也是能夠的。
請記住,JavaScript 會等到服務器響應就緒才繼續執行。若是服務器繁忙或緩慢,應用程序會掛起或中止。
注意:當您使用 async=false 時,請不要編寫 onreadystatechange 函數 - 把代碼放到send()
語句後面便可:
xmlhttp.open("GET","ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
xhr.status
狀態碼,如200,304,404等; xhr.responseText
與xhr.responseXML
都表示響應主體。 如需得到來自服務器的響應,請使用 XMLHttpRequest 對象的responseText
或responseXML
屬性。
屬性 | 描述 |
---|---|
responseText | 得到字符串形式的響應數據。 |
responseXML | 得到 XML 形式的響應數據。 |
若是來自服務器的響應並不是 XML,請使用responseText
屬性。
responseText
屬性返回字符串形式的響應,所以您能夠這樣使用:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tryrun 1</title> </head> <body> <div id="view"> <p>點擊下面的按鈕,將 Ajax 請求回來的數據更新在該文本內</p> </div> <button type="button" id="btn">發起 Ajax 請求</button> <script> document.getElementById("btn").onclick = ajaxRequest; function ajaxRequest () { var xhr = new XMLHttpRequest(); xhr.open("GET", "https://www.w3cschool.cn/statics/demosource/ajax_info.txt", true); xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById("view").innerHTML = xhr.responseText; } } } </script> </body>
提示:對於responseText
屬性,只有當 readyState
屬性值變爲4時,responseText
屬性纔可用,由於這代表AJAX請求已經結束!
若是來自服務器的響應是 XML,並且須要做爲 XML 對象進行解析,請使用responseXML
屬性:
請求 cd_catalog.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;
當發送一個請求後,客戶端須要肯定這個請求何時會完成,所以,XMLHttpRequest對象提供了onreadystatechange
事件機制來捕獲請求的狀態,繼而實現響應。
當請求被髮送到服務器時,咱們須要執行一些基於響應的任務。
每當readyState
改變時,就會觸發onreadystatechange
事件。
readyState
屬性存有 XMLHttpRequest 的狀態信息。
下面是 XMLHttpRequest 對象的三個重要的屬性:
屬性 | 描述 |
---|---|
onreadystatechange |
存儲函數(或函數名),每當readyState 屬性改變時,就會調用該函數。 |
readyState |
存有 XMLHttpRequest 的狀態。從 0 到 4 發生變化。
|
status |
200: "OK" 404: 未找到頁面 |
0:請求未初始化
此階段確認XMLHttpRequest對象是否建立,併爲調用open()
方法進行未初始化做好準備,值爲0表示對象已經存在,不然瀏覽器會報錯:對象不存在。
1:服務器鏈接已創建
此階段對XMLHttpRequest對象進行初始化,即調用open()
方法,根據參數(method,url,true)
完成對象狀態的設置。並調用send()
方法開始向服務端發送請求。
值爲1表示正在向服務端發送請求。
2:請求已接收
此階段接收服務器端的響應數據。但得到的還只是服務端響應的原始數據,並不能直接在客戶端使用。
值爲2表示已經接收徹底部響應數據,併爲下一階段對數據解析做好準備。
3:請求處理中
此階段解析接收到的服務器端響應數據即根據服務器端響應頭部返回的MIME類型把數據轉換成能經過responseBody
,responseText
或responseXML
的屬性存取的格式,爲在客戶端調用做好準備。
狀態3表示正在解析數據。
4:請求已完成,且響應已就緒
此階段確認所有數據都已經解析爲客戶端可用的格式,解析已經完成。值爲4表示數據解析完畢,能夠經過的XMLHttpRequest對象的屬性取得數據。
概而括之,整個XMLHttpRequest對象的生命週期應該包含以下階段:
在onreadystatechange
事件中,咱們規定當服務器響應已作好被處理的準備時所執行的任務。
當readyState
等於 4 且狀態爲 200 時,表示響應已就緒:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tryrun 1</title> </head> <body> <div id="view"> <p>點擊下面的按鈕,將 Ajax 請求回來的數據更新在該文本內</p> </div> <button type="button" id="btn">發起 Ajax 請求</button> <script> document.getElementById("btn").onclick = ajaxRequest; function ajaxRequest () { var xhr = new XMLHttpRequest(); xhr.open("GET", "https://www.w3cschool.cn/statics/demosource/ajax_info.txt", true); xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById("view").innerHTML = xhr.responseText; } } } </script> </body>
注意:onreadystatechange
事件被觸發 5 次(0 - 4),對應着readyState
的每一個變化。
提示:XHR.readyState狀態的變化以下:
open()
。 send()
。
回調函數是一種以參數形式傳遞給另外一個函數的函數。
若是您的網站上存在多個 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;
}
});
}
數據庫:數據庫可視爲電子化的文件櫃-存儲電子文件的處所,用戶能夠對文件中的數據進行新增,截取,更新,刪除等操做。
常見的型關係數據庫有MySQL,SQLSERVER,Oracle,Sybase,DB2等。
您能夠在w3cschool首頁查找使用數據庫的相關教程。
AJAX 可用來與數據庫進行動態通訊。
經過本節內容,你將瞭解 AJAX 動態加載數據庫的相關知識。
下面的例子將演示網頁如何經過 AJAX 從數據庫讀取信息:請在下面的下拉列表中選擇一個客戶:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function showCustomer(str) { var xmlhttp; if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } 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("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","/statics/demosource/getcustomer.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form action=""> <select name="customers" onchange="showCustomer(this.value)" style="font-family:Verdana, Arial, Helvetica, sans-serif;"> <option value="APPLE">Apple Computer, Inc.</option> <option value="BAIDU ">BAIDU, Inc</option> <option value="Canon">Canon USA, Inc.</option> <option value="Google">Google, Inc.</option> <option value="Nokia">Nokia Corporation</option> <option value="SONY">Sony Corporation of America</option> </select> </form> <br> <div id="txtHint">Customer info will be listed here...</div> </body> </html>
當用戶在上面的下拉列表中選擇某個客戶時,會執行名爲 "showCustomer()" 的函數。該函數由 "onchange" 事件觸發:
function showCustomer(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getcustomer.html?q="+str,true);
xmlhttp.send();
}
showCustomer() 函數執行如下任務:
檢查是否已選擇某個客戶
建立 XMLHttpRequest 對象
當服務器響應就緒時執行所建立的函數
把請求發送到服務器上的文件
請注意咱們向 URL 添加了一個參數 q (帶有輸入域中的內容)
AJAX 可用來與 XML 文件進行交互式通訊。
本節經過解析實例來使你瞭解AJAX是如何讀取XML文件的信息的!
咱們首先實例化或建立XMLHttpRequest(XHR)對象實例化或建立JavaScript的對象:
xhr = new XMLHttpRequest();
可是,IE5和IE6不支持XMLHttpRequest,您須要以不一樣的方式實例化它:
xhr = new ActiveXObject ("Msxml2.XMLHTTP")
注:Windows 10附帶的Microsoft Edge默認Web瀏覽器天然支持XMLHttpRequest的。)
所以,實例化XHR變得有點麻煩,你必須首先測試用戶的瀏覽器如何支持它。
var xhr;
if(window.XMLHttpRequest){ //適用於大多數現代Web瀏覽器
xhr = new XMLHttpRequest();
}
else(window.ActiveXObject){ //對於IE5,IE6
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
下面的例子將演示網頁如何使用 AJAX 來讀取來自 XML 文件的信息:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function loadXMLDoc(url) { var xmlhttp; var txt,x,xx,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) { txt="<table border='1'><tr><th>Title</th><th>Artist</th></tr>"; x=xmlhttp.responseXML.documentElement.getElementsByTagName("CD"); for (i=0;i<x.length;i++) { txt=txt + "<tr>"; xx=x[i].getElementsByTagName("TITLE"); { try { txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>"; } catch (er) { txt=txt + "<td> </td>"; } } xx=x[i].getElementsByTagName("ARTIST"); { try { txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>"; } catch (er) { txt=txt + "<td> </td>"; } } txt=txt + "</tr>"; } txt=txt + "</table>"; document.getElementById('txtCDInfo').innerHTML=txt; } } xmlhttp.open("GET",url,true); xmlhttp.send(); } </script> </head> <body> <div id="txtCDInfo"> <button onclick="loadXMLDoc('/statics/demosource/cd_catalog.xml')">Get CD info</button> </div> </body> </html>
當用戶點擊上面的"得到 CD 信息"這個按鈕,就會執行loadXMLDoc()
函數。
loadXMLDoc()
函數建立 XMLHttpRequest 對象,添加當服務器響應就緒時執行的函數,並將請求發送到服務器。
當服務器響應就緒時,會構建一個 HTML 表格,從 XML 文件中提取節點(元素),最後使用已經填充了 XML 數據的 HTML 表格來更新txtCDInfo
佔位符:
function loadXMLDoc(url) { var xmlhttp; var txt,xx,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) { txt="<table border='1'><tr><th>Title</th><th>Artist</th></tr>"; x=xmlhttp.responseXML.documentElement.getElementsByTagName("CD"); for (i=0;i<x.length;i++) { txt=txt + "<tr>"; xx=x[i].getElementsByTagName("TITLE"); { try { txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>"; } catch (er) { txt=txt + "<td> </td>"; } } xx=x[i].getElementsByTagName("ARTIST"); { try { txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>"; } catch (er) { txt=txt + "<td> </td>"; } } txt=txt + "</tr>"; } txt=txt + "</table>"; document.getElementById('txtCDInfo').innerHTML=txt; } } xmlhttp.open("GET",url,true); xmlhttp.send(); }
上面這個例子中使用的服務器頁面其實是一個名爲 "cd_catalog.xml" XML 文件。
一個簡單的AJAX實例
建立一個簡單的XMLHttpRequest,從一個TXT文件中返回數據。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tryrun 1</title> </head> <body> <div id="view"> <p>點擊下面的按鈕,將 Ajax 請求回來的數據更新在該文本內</p> </div> <button type="button" id="btn">發起 Ajax 請求</button> <script> document.getElementById("btn").onclick = ajaxRequest; function ajaxRequest () { var xhr = new XMLHttpRequest(); xhr.open("GET", "https://www.w3cschool.cn/statics/demosource/ajax_info.txt", true); xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById("view").innerHTML = xhr.responseText; } } } </script> </body>
用AJAX加載 XML 文件
建立一個簡單的XMLHttpRequest,從一個XML文件中返回數據。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function loadXMLDoc(url) { 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('A1').innerHTML=xmlhttp.status; document.getElementById('A2').innerHTML=xmlhttp.statusText; document.getElementById('A3').innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET",url,true); xmlhttp.send(); } </script> </head> <body> <h2>Retrieve data from XML file</h2> <p><b>Status:</b><span id="A1"></span></p> <p><b>Status text:</b><span id="A2"></span></p> <p><b>Response:</b><span id="A3"></span></p> <button onclick="loadXMLDoc('note.xml')">Get XML data</button> </body> </html>
用AJAX進行一次 HEAD 請求
檢索資源(文件)的頭信息。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function loadXMLDoc(url) { 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('p1').innerHTML=xmlhttp.getAllResponseHeaders(); } } xmlhttp.open("GET",url,true); xmlhttp.send(); } </script> </head> <body> <p id="p1">The getAllResponseHeaders() function returns the header information of a resource, like length, server-type, content-type, last-modified, etc.</p> <button onclick="loadXMLDoc('/statics/demosource/ajax_info.txt')">Get header information</button> </body> </html>
用AJAX進行一次指定的 HEAD 請求
檢索資源(文件)的指定頭信息。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function loadXMLDoc(url) { 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('p1').innerHTML="Last modified: " + xmlhttp.getResponseHeader('Last-Modified'); } } xmlhttp.open("GET",url,true); xmlhttp.send(); } </script> </head> <body> <p id="p1">The getResponseHeader() function is used to return specific header information from a resource, like length, server-type, content-type, last-modified, etc.</p> <button onclick="loadXMLDoc('/statics/demosource/ajax_info.txt')">Get "Last-Modified" information</button> </body> </html>
用AJAX從ASP 文件返回數據
當用戶在文本框內鍵入字符時網頁如何與Web服務器進行通訊
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function showHint(str) { var xmlhttp; if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; } 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("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","/statics/demosource/gethint.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <h3>Start typing a name in the input field below:</h3> <form action=""> First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" /> </form> <p>Suggestions: <span id="txtHint"></span></p> </body> </html>
用AJAX從數據庫返回數據
用AJAX網頁如何獲取數據庫中的信息
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function showCustomer(str) { var xmlhttp; if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } 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("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","/statics/demosource/getcustomer.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form action=""> <select name="customers" onchange="showCustomer(this.value)" style="font-family:Verdana, Arial, Helvetica, sans-serif;"> <option value="APPLE">Apple Computer, Inc.</option> <option value="BAIDU ">BAIDU, Inc</option> <option value="Canon">Canon USA, Inc.</option> <option value="Google">Google, Inc.</option> <option value="Nokia">Nokia Corporation</option> <option value="SONY">Sony Corporation of America</option> </select> </form> <br> <div id="txtHint">Customer info will be listed here...</div> </body> </html>
用AJAX從XML 文件返回數據
建立一個XMLHttpRequest從XML文件中檢索數據並顯示在一個HTML表格中。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function loadXMLDoc(url) { var xmlhttp; var txt,x,xx,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) { txt="<table border='1'><tr><th>Title</th><th>Artist</th></tr>"; x=xmlhttp.responseXML.documentElement.getElementsByTagName("CD"); for (i=0;i<x.length;i++) { txt=txt + "<tr>"; xx=x[i].getElementsByTagName("TITLE"); { try { txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>"; } catch (er) { txt=txt + "<td> </td>"; } } xx=x[i].getElementsByTagName("ARTIST"); { try { txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>"; } catch (er) { txt=txt + "<td> </td>"; } } txt=txt + "</tr>"; } txt=txt + "</table>"; document.getElementById('txtCDInfo').innerHTML=txt; } } xmlhttp.open("GET",url,true); xmlhttp.send(); } </script> </head> <body> <div id="txtCDInfo"> <button onclick="loadXMLDoc('/statics/demosource/cd_catalog.xml')">Get CD info</button> </div> </body> </html>
用callback函數的AJAX實例
用一個callback函數建立一個XMLHttpRequest,並從一個TXT文件中檢索數據。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> var xmlhttp; function loadXMLDoc(url,cfunc) { if (window.XMLHttpRequest) {// IE7+, Firefox, Chrome, Opera, Safari 代碼 xmlhttp=new XMLHttpRequest(); } else {// IE6, IE5 代碼 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=cfunc; xmlhttp.open("GET",url,true); xmlhttp.send(); } function myFunction() { loadXMLDoc("/statics/demosource/ajax_info.txt",function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }); } </script> </head> <body> <div id="myDiv"><h2>使用 AJAX 修改文本內容</h2></div> <button type="button" onclick="myFunction()">修改內容</button> </body> </html>
AJAX提交form表單,這在平常項目中是常常用到的。前臺不管是簡單的html、jsp或者使用了easyui框架,只要是提交表單通常都會使用到AJAX。
一、無返回結果的,就是把表單數據直接提交給後臺,讓後臺直接處理;
最簡單的就是$(「#formid」).submit();直接將form表單提交到後臺。
二、返回有結果的,這種狀況下,後臺無論是執行成功仍是失敗,最終的信息都須要返回到前臺。
第二種是使用最多的一種,由於程序的執行成功與否都須要給用戶提示,程序通常也都是多步完成的,執行完插入操做,須要發起流程,這就須要在界面上判斷成功與否。ajax自己屬於有返回結果的一類,其中的success
方法就是處理後臺返回結果的。
一、將form表單數據序列化
<span style="font-size:18px;"> $.ajax({ type: "POST", url:your-url, data:$('#yourformid').serialize(), async: false, error: function(request) { alert("Connection error"); }, success: function(data) { //接收後臺返回的結果 } });</span>
須要注意的是,使用這種方法的前提是form表單中的項必定要有name屬性,後臺獲取的鍵值對爲 key=name 值,value=各項值。
注意:不管是
input
標籤仍是span
標籤或者其餘標籤,必定要有name
屬性,沒有name
屬性後臺是獲取不到該項的。
二、經過窗口查找form提交
<span style="font-size:18px;"> // 提交表單 var obj = document.getElementById("xx_iframe").contentWindow; obj.$("#yourform").form("submit",{ success :function(data){ //對結果處理 } });</span>
由於在當前界面上彈出對話框,而後在對話框上的按鈕觸發對話框中表單提交,對話框又是連接的另外的html頁面,如此經過$(「#formid」)的方式是找不到對話框中的form的,所以這種狀況下只能使用這種方式提交表單。
另外ajax中封裝的get
,post
請求也都屬於有返回結果的一類。
總的來講,無返回結果的和有返回結果的(將form表單數據序列化+經過窗口實現form提交),form表單都必需要有name
屬性。
在jQuery中,AJAX常見的請求方式主要有一下4種:
$.ajax()
只有一個參數:參數key/value
對象,包含各配置及回調函數信息。
若是你指定了dataType
選項,那麼須要保證服務器返回正確的MIME信息,(如 xml 返回 "text/xml")。
實例:
保存數據到服務器,成功時顯示信息。
$.ajax({
type: "post",
dataType: "html",
url: '/Resources/GetList.ashx',
data: dataurl,
success: function (data) {
if (data != "") {
$("#pager").pager({ pagenumber: pagenumber, pagecount: data.split("$")[1], buttonClickCallback: PageClick });
$("#anhtml").html(data.split("$")[0]);
}
}
});
相比於複雜的$.ajax
而言,GET
請求功能則顯得更加簡單,請求成功時可調用回調函數。固然若是須要在出錯時執行函數,那麼還請使用$.ajax
。
實例:
$.get("test.cgi", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
POST
請求功能也相對比較簡單,請求成功時可調用回調函數。若是須要在出錯時執行函數,那麼請使用$.ajax
請求。
實例:
$.post("/Resources/addfriend.ashx", { "fid": fids, "fname": fnames, "tuid": tuids, "tuname": tunames }, function (data) {
if (data == "ok") {
alert("添加成功!");
}
})
實例:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data){ $.each(data.items, function(i,item){ $("<img/>").attr("src", item.media.m).appendTo("#images"); if ( i == 3 ) return false; }); });
一、什麼是AJAX?
AJAX表明異步JavaScript和XML。它是一組用於異步顯示數據的相關技術。換句話說,它在不從新加載網頁的狀況下發送和檢索數據。
二、AJAX有哪些優勢?
三、AJAX有哪些缺點?
四、目前市場上運行的AJAX的真實Web應用程序是什麼?
五、AJAX有哪些安全問題?
六、同步和異步請求有什麼區別?
同步請求會阻止用戶,直到檢索到響應,而異步不會阻止用戶。
七、AJAX使用了哪些技術?
八、XMLHttpRequest的目的是什麼?
九、XMLHttpRequest的屬性是什麼?
下面給出了XMLHttpRequest對象的重要屬性。
onReadyStateChange
- 只要readystate屬性發生變化,就會調用它。readyState
- 表示請求的狀態。responseText
- 它將響應做爲文本返回。responseXML
- 它以XML格式返回響應。status
- 返回請求的狀態編號。statusText
- 返回狀態的詳細信息。十、XMLHttpRequest的重要方法是什麼?
abort()
- 用於取消當前請求。getAllResponseHeaders()
- 返回標題詳細信息。getResponseHeader()
- 返回特定的標題詳細信息。open()
- 用於打開請求。send()
- 用於發送請求。setRequestHeader()
- 它添加了請求標頭。十一、XMLHttpRequest使用的open()方法有哪些類型?
open(method,URL)
- 它打開指定get或post方法和URL的請求。open(method,URL,async)
- 它與上面相同可是指定異步或不指定。open(method,URL,async,userName,password)
- 與上面相同,但指定用戶名和密碼。十二、XMLHttpRequest使用的send()方法有哪些類型?
send()
- 它發送get請求send(string)
- 發送帖子請求。1三、回調函數在AJAX中的做用是什麼?
回調函數將函數做爲參數傳遞給另外一個函數。若是咱們必須在網站上執行各類AJAX任務,那麼咱們能夠建立一個用於執行XMLHttpRequest的函數和一個用於執行每一個AJAX任務的回調函數。
1四、AJAX中的JSON是什麼?
JSON表明JavaScript Object Notation。在AJAX中,它用於在瀏覽器和服務器之間交換數據。它很容易理解,數據交換比XML快。它支持數組,對象,字符串,數字和值。
request.onreadystatechange = function (){
if(request.readyState == 4)
{
var jsonObj = JSON .parse(request.responseText); // JSON.parse()返回JSON對象
的document.getElementById( 「日期」).innerHTML = jsonObj .date;
的document.getElementById( 「時間」).innerHTML = jsonObj 。時間;
}
}
1五、調試AJAX應用程序的工具備哪些?
有幾種用於調試AJAX應用程序的工具。
1六、AJAX中的回發類型有哪些?
在AJAX中有兩種類型的回發。
1七、AJAX中請求的準備狀態有哪些?
在AJAX中有5個請求的就緒狀態。
1八、常見的AJAX框架是什麼?
1九、你如何測試AJAX代碼?
JUnit是客戶端JavaScript的開源單元測試框架。須要建立測試用例。單元測試用例是一個代碼,用於確保程序邏輯按預期工做。
20、JavaScript和AJAX有什麼區別?
JavaScript | AJAX |
---|---|
JavaScript是一種基於對象的腳本語言。 | AJAX是一組相互關聯的技術,如JavaScript,XML,HTML,CSS等 |
它請求服務器並等待響應。 | 它向服務器發送請求,不等待響應。 |
從新加載頁面時會佔用更多帶寬。 | 它不會從新加載頁面,所以佔用的帶寬更少。 |
咱們能夠經過AJAX代碼獲取JSON數據。AJAX提供了異步獲取響應的工具。它不會從新加載頁面並節省帶寬。
讓咱們看一個使用AJAX代碼獲取JSON數據的簡單示例。
<html> <head> <meta content="text/html; charset=utf-8"> <title>AJAX JSON by Javatpoint</title> <script type="application/javascript"> function load() { var url = "http://date.jsontest.com/";//use any url that have json data var request; if(window.XMLHttpRequest){ request=new XMLHttpRequest();//for Chrome, mozilla etc } else if(window.ActiveXObject){ request=new ActiveXObject("Microsoft.XMLHTTP");//for IE only } request.onreadystatechange = function(){ if (request.readyState == 4 ) { var jsonObj = JSON.parse(request.responseText);//JSON.parse() returns JSON object document.getElementById("date").innerHTML = jsonObj.date; document.getElementById("time").innerHTML = jsonObj.time; } } request.open("GET", url, true); request.send(); } </script> </head> <body> Date: <span id="date"></span><br/> Time: <span id="time"></span><br/> <button type="button" onclick="load()">Load Information</button> </body> </html>
AJAX的使用率正在快速增加,這也是它會包含許多問題的緣由。咱們但願隨着時間的推移,這些問題將獲得解決,AJAX將成爲Web應用程序的理想選擇。
在本節咱們列出了AJAX目前遇到的一些問題。
(1)複雜性增長了
(2)基於AJAX的應用程序可能難以調試,測試和維護
(3)工具包/框架還沒有成熟
(4)還沒有標準化XMLHttpRequest
(5)舊瀏覽器中不支持XMLHttpRequest
(6)JavaScript技術依賴性和不兼容性
(7)JavaScript代碼對黑客可見
服務器端
客戶端