Ajax的初步使用
定義(來自MDN)
(異步JavaScript和XML)Asynchronous JavaScript + XML, 其本身不是一種新技術(shù)妙真,而是一個在 2005年被Jesse James Garrett提出的新術(shù)語朽缴,用來描述一種使用現(xiàn)有技術(shù)集合的‘新’方法凶朗,包括: HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, 以及最重要的 XMLHttpRequest object洞难。當(dāng)使用結(jié)合了這些技術(shù)的AJAX模型以后, 網(wǎng)頁程序能夠快速地將漸步更新呈現(xiàn)在用戶界面上快耿,不需要重載(刷新)整個頁面盏袄。這使得程序能夠更快地回應(yīng)用戶的操作。
盡管X在Ajax中代表XML, 但由于JSON的許多優(yōu)勢葱她,比如更加輕量以及作為Javascript的一部分撩扒,目前JSON的使用比XML更加普遍。JSON和XML都被用于在Ajax模型中打包信息吨些。
XMLHttpRequest對象
XMLHttpRequest對象充當(dāng)著瀏覽器中的腳本(客戶端)與服務(wù)器之間的中間人角色搓谆。JS通過這個對象可以自己發(fā)送請求,同時也自己處理響應(yīng)锤灿。
XHR對象在IE中可能會遇到MSXML2.XMLHttp挽拔、MSXML2.XMLHttp.3.0、MSXML2.XMLHttp.6.0三個不同版本(IE7以前)但校。IE7+螃诅、Firefox、Opera、Chrome和Safari都支持原生的XHR對象术裸,在這些倘是;瀏覽器中創(chuàng)建XHR對象則用XMLHttpRequest構(gòu)造函數(shù)。
<pre class="md-fences md-end-block" cid="n12" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Consolas, "Liberation Mono", Courier, monospace; font-size: 0.9em; white-space: pre; text-align: left; break-inside: avoid; display: block; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(221, 221, 221); border-radius: 3px; padding: 8px 1em 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;" lang="javascript" contenteditable="false">function getHTTPObject() {
if (typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function () {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0");}
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0");}
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP");}
catch (e) {}
return false;
}
return new XMLHttpRequest();
}</pre>
XHR
XHR對象第一個方法是open方法袭艺,它用來指定服務(wù)器上將要訪問的文件搀崭,指定請求類型:GET、POST猾编。
xhr.open(“get”,"example.php",false)
第一個參數(shù)是要發(fā)送的請求的類型瘤睹、第二個數(shù)請求的URL、第三個請求時表示是否異步發(fā)送請求的布爾值答倡。
<pre class="md-fences md-end-block" cid="n20" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Consolas, "Liberation Mono", Courier, monospace; font-size: 0.9em; white-space: pre; text-align: left; break-inside: avoid; display: block; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(221, 221, 221); border-radius: 3px; padding: 8px 1em 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;" lang="javascript" contenteditable="false">
function getNewContent () {
var request = getHTTPObject();
if (request) {
request.open("GET","example.txt",true);
request.onreadystatechange = function() {
if(request.readyState == 4||request.status >= 200 && request.status <300 || request.status == 304) {
var para = document.createElement("p");
var txt = document.createTextNode(request.responseText);
para.appendChild(txt);
document.getElementById('new').appendChild(para);
}
};
request.send(null);
}else {
alert('Sorry,your browser doesn`t suppor XMLHttpRequset');
}
}
addLoadEvent(getNewContent);</pre>
onreadystatechange是一個事件處理函數(shù)轰传,他會在服務(wù)器給XHR對象送回響應(yīng)的時候被處罰執(zhí)行。在這個處理函數(shù)中瘪撇,可以根據(jù)服務(wù)器的具體響應(yīng)做相應(yīng)的處理获茬。
收到響應(yīng)后,響應(yīng)數(shù)據(jù)會自動填充XHR對象的屬性倔既,相關(guān)屬性簡介如下恕曲。
responseText:獲得字符串形式的響應(yīng)數(shù)據(jù)。
responseXML:獲得 XML 形式的響應(yīng)數(shù)據(jù)渤涌。
status:響應(yīng)的HTTP狀態(tài)佩谣。
sstatusText:HTTP狀態(tài)的說明。
收到響應(yīng)后歼捏,第一部檢查status屬性稿存,已確定響應(yīng)已經(jīng)成功返回。一般來說瞳秽,將HTTP狀態(tài)代碼為200作為成功響應(yīng)的標(biāo)志。池外率翅,狀態(tài)代碼為304表示請求的資源沒有被修改练俐,可以直接使用瀏覽器中緩存的版本,意味著響應(yīng)也是有效的冕臭。
readyState屬性表示請求/響應(yīng)過程中的當(dāng)前活動階段腺晾。這個屬性可取的值如下
0: 請求未初始化
1: 服務(wù)器連接已建立
2: 請求已接收
3: 請求處理中
4: 請求已完成,且響應(yīng)已就緒
通常我們只對值為4的階段感興趣辜贵,這時候所有數(shù)據(jù)已經(jīng)就緒悯蝉。
GET請求
最常用于向服務(wù)器查詢某些信息。
POST請求
通常用于向服務(wù)器發(fā)送應(yīng)該被保存的數(shù)據(jù)托慨。
Ajax的同源策略
石頭XHR對象發(fā)送的請求只能訪問與其所在的HTML處于同一域中的數(shù)據(jù)鼻由,不能向其他域發(fā)送請求。此外,游戲瀏覽器會限制Ajax請求使用的協(xié)議蕉世。例如蔼紧,Chrome中,使用file://協(xié)議從自己的硬盤里加載emample.txt文件狠轻,會看到"Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.(跨域請求只支持HTTP協(xié)議)的錯誤消息"奸例。
XMLHttpRequest2級
FormData
表單數(shù)據(jù)的序列化。創(chuàng)建FormData()對象向楼,利用data.append()方法接受兩個參數(shù):鍵和值查吊,分別對應(yīng)表單字段的名字和字段中包含的值。
超時設(shè)定
timeout屬性湖蜕,表示請求在等待響應(yīng)多少毫秒后就終止菩貌。在設(shè)置數(shù)值后,如果在規(guī)定時間內(nèi)瀏覽器沒有收到相應(yīng)重荠,就會觸發(fā)timeout事件箭阶,進(jìn)而調(diào)用ontimeout事件處理程序。
overrideMimeType()方法
重寫XHR響應(yīng)的MIME類型
進(jìn)度事件
load事件
progress事件