詳解JavaScript實現異步Ajax
一、什么是 AJAX ?
AJAX = 異步 JavaScript 和 XML。AJAX 是一種用于創(chuàng)建快速動態(tài)網頁的技術。
通過在后臺與服務器進行少量數據交換,AJAX 可以使網頁實現異步更新。這意味著可以在不重新加載整個網頁的情況下,對網頁的某部分進行更新。傳統(tǒng)的網頁(不使用 AJAX)如果需要更新內容,必需重載整個網頁面。
有很多使用 AJAX 的應用程序案例:新浪微博、Google 地圖、開心網等等。
1、AJAX是基于現有的Internet標準
AJAX是基于現有的Internet標準,并且聯(lián)合使用它們:
- XMLHttpRequest 對象 (異步的與服務器交換數據)
- JavaScript/DOM (信息顯示/交互)
- CSS (給數據定義樣式)
- XML (作為轉換數據的格式)
注意:AJAX應用程序與瀏覽器和平臺無關的!
2、AJAX 工作原理

二、AJAX - 創(chuàng)建 XMLHttpRequest 對象
1、XMLHttpRequest 對象
XMLHttpRequest 是 AJAX 的基礎。所有現代瀏覽器均支持 XMLHttpRequest 對象(IE5 和 IE6 使用 ActiveXObject)。
XMLHttpRequest 用于在后臺與服務器交換數據。這意味著可以在不重新加載整個網頁的情況下,對網頁的某部分進行更新。
2、創(chuàng)建 XMLHttpRequest 對象
所有現代瀏覽器(IE7+、Firefox、Chrome、Safari 以及 Opera)均內建 XMLHttpRequest 對象。
創(chuàng)建 XMLHttpRequest 對象的語法:
variable=new XMLHttpRequest();
老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 對象:
variable=new ActiveXObject("Microsoft.XMLHTTP");為了應對所有的現代瀏覽器,包括 IE5 和 IE6,請檢查瀏覽器是否支持 XMLHttpRequest 對象。如果支持,則創(chuàng)建 XMLHttpRequest 對象。如果不支持,則創(chuàng)建 ActiveXObject :
var xmlhttp;
if (window.XMLHttpRequest)
{
// IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執(zhí)行代碼
xmlhttp=new XMLHttpRequest();
}
else
{
// IE6, IE5 瀏覽器執(zhí)行代碼
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}三、向服務器發(fā)送請求請求
1、向服務器發(fā)送請求
XMLHttpRequest 對象用于和服務器交換數據。
如需將請求發(fā)送到服務器,我們使用 XMLHttpRequest 對象的 open() 和 send() 方法:
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();方法:
open(method,url,async):規(guī)定請求的類型、URL 以及是否異步處理請求。
- method:請求的類型;GET 或 POST
- url:文件在服務器上的位置
- async:true(異步)或 false(同步)
send(string):將請求發(fā)送到服務器。string:僅用于 POST 請求
注意:open() 方法的 url 參數是服務器上文件的地址:
xmlhttp.open("GET","ajax_test.html",true);該文件可以是任何類型的文件,比如 .txt 和 .xml,或者服務器腳本文件,比如 .asp 和 .php (在傳回響應之前,能夠在服務器上執(zhí)行任務)。
2、GET 還是 POST?
與 POST 相比,GET 更簡單也更快,并且在大部分情況下都能用。
然而,在以下情況中,請使用 POST 請求:
- 無法使用緩存文件(更新服務器上的文件或數據庫)
- 向服務器發(fā)送大量數據(POST 沒有數據量限制)
- 發(fā)送包含未知字符的用戶輸入時,POST 比 GET 更穩(wěn)定也更可靠
3、GET 請求
一個簡單的 GET 請求:
xmlhttp.open("GET","/try/ajax/demo_get.php",true);
xmlhttp.send();在上面的例子中,您可能得到的是緩存的結果。
為了避免這種情況,請向 URL 添加一個唯一的 ID:
xmlhttp.open("GET","/try/ajax/demo_get.php?t=" + Math.random(),true);
xmlhttp.send();如果您希望通過 GET 方法發(fā)送信息,請向 URL 添加信息:
xmlhttp.open("GET","/try/ajax/demo_get2.php?fname=Henry&lname=Ford",true);
xmlhttp.send();4、POST 請求
一個簡單 POST 請求:
xmlhttp.open("POST","/try/ajax/demo_post.php",true);
xmlhttp.send();如果需要像 HTML 表單那樣 POST 數據,請使用 setRequestHeader() 來添加 HTTP 頭。然后在 send() 方法中規(guī)定您希望發(fā)送的數據:
xmlhttp.open("POST","/try/ajax/demo_post2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");5、異步 - True 或 False?
AJAX 指的是異步 JavaScript 和 XML(Asynchronous JavaScript and XML)。
XMLHttpRequest 對象如果要用于 AJAX 的話,其 open() 方法的 async 參數必須設置為 true:
xmlhttp.open("GET","ajax_test.html",true);對于 web 開發(fā)人員來說,發(fā)送異步請求是一個巨大的進步。很多在服務器執(zhí)行的任務都相當費時。AJAX 出現之前,這可能會引起應用程序掛起或停止。
通過 AJAX,JavaScript 無需等待服務器的響應,而是:
- 在等待服務器響應時執(zhí)行其他腳本
- 當響應就緒后對響應進行處理
當使用 async=true 時,請規(guī)定在響應處于 onreadystatechange 事件中的就緒狀態(tài)時執(zhí)行的函數:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/try/ajax/ajax_info.txt",true);
xmlhttp.send();注意:當您使用 async=false 時,請不要編寫 onreadystatechange 函數 - 把代碼放到 send() 語句后面即可:
xmlhttp.open("GET","/try/ajax/ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;四、AJAX - 服務器 響應
如需獲得來自服務器的響應,請使用 XMLHttpRequest 對象的 responseText 或 responseXML 屬性。
- responseText:獲得字符串形式的響應數據。
- responseXML:獲得 XML 形式的響應數據。
1、responseText 屬性
如果來自服務器的響應并非 XML,請使用 responseText 屬性。
responseText 屬性返回字符串形式的響應,因此您可以這樣使用:
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;2、responseXML 屬性
如果來自服務器的響應是 XML,而且需要作為 XML 對象進行解析,請使用 responseXML 屬性:
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;五、AJAX - onreadystatechange 事件
當請求被發(fā)送到服務器時,我們需要執(zhí)行一些基于響應的任務。
每當 readyState 改變時,就會觸發(fā) onreadystatechange 事件。
readyState 屬性存有 XMLHttpRequest 的狀態(tài)信息。
1、XMLHttpRequest 對象的三個重要的屬性:
1、onreadystatechange:存儲函數(或函數名),每當 readyState 屬性改變時,就會調用該函數。
2、readyState:存有 XMLHttpRequest 的狀態(tài)。從 0 到 4 發(fā)生變化。
- 0: 請求未初始化
- 1: 服務器連接已建立
- 2: 請求已接收
- 3: 請求處理中
- 4: 請求已完成,且響應已就緒
3、status:狀態(tài)。200: "OK";404: 未找到頁面
在 onreadystatechange 事件中,我們規(guī)定當服務器響應已做好被處理的準備時所執(zhí)行的任務。
當 readyState 等于 4 且狀態(tài)為 200 時,表示響應已就緒:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}注意: onreadystatechange 事件被觸發(fā) 4 次(0 - 4), 分別是: 0-1、1-2、2-3、3-4,對應著 readyState 的每個變化。
2、使用回調函數
回調函數是一種以參數形式傳遞給另一個函數的函數。
如果您的網站上存在多個 AJAX 任務,那么您應該為創(chuàng)建 XMLHttpRequest 對象編寫一個標準的函數,并為每個 AJAX 任務調用該函數。
該函數調用應該包含 URL 以及發(fā)生 onreadystatechange 事件時執(zhí)行的任務(每次調用可能不盡相同):
function myFunction()
{
loadXMLDoc("/try/ajax/ajax_info.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
});
}六、javascript 腳本化的HTTP----ajax的基石
1、建XMLHttpRequest對象
// This is a list of XMLHttpRequest-creation factory functions to try
HTTP._factories = [
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];
// When we find a factory that works, store it here.
HTTP._factory = null;
// Create and return a new XMLHttpRequest object.
//
// The first time we're called, try the list of factory functions until
// we find one that returns a non-null value and does not throw an
// exception. Once we find a working factory, remember it for later use.
//
HTTP.newRequest = function() {
if (HTTP._factory != null) return HTTP._factory();
for(var i = 0; i < HTTP._factories.length; i++) {
try {
var factory = HTTP._factories[i];
var request = factory();
if (request != null) {
HTTP._factory = factory;
return request;
}
}
catch(e) {
continue;
}
}
// If we get here, none of the factory candidates succeeded,
// so throw an exception now and for all future calls.
HTTP._factory
= function() {
throw new Error("XMLHttpRequest not supported");
}
HTTP._factory(); // Throw an error
}2、Get請求
HTTP.get = function(url, callback, options) {
var request = HTTP.newRequest();
var n = 0;
var timer;
if (options.timeout)
timer = setTimeout(function() {
request.abort();
if (options.timeoutHandler)
options.timeoutHandler(url);
},
options.timeout);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (timer) clearTimeout(timer);
if (request.status == 200) {
callback(HTTP._getResponse(request));
}
else {
if (options.errorHandler)
options.errorHandler(request.status,
request.statusText);
else callback(null);
}
}
else if (options.progressHandler) {
options.progressHandler(++n);
}
}
var target = url;
if (options.parameters)
target += "?" + HTTP.encodeFormData(options.parameters)
request.open("GET", target);
request.send(null);
};1、GET工具
//getText()工具
HTTP.getText = function(url, callback) {
var request = HTTP.newRequest();
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
callback(request.responseText);
}
}
request.open("GET", url);
request.send(null);
}
//getXML()工具
HTTP.getXML = function(url, callback) {
var request = HTTP.newRequest();
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
callback(request.responseXML);
}
}
request.open("GET", url);
request.send(null);
}3、POST請求
/**
* Send an HTTP POST request to the specified URL, using the names and values
* of the properties of the values object as the body of the request.
* Parse the server's response according to its content type and pass
* the resulting value to the callback function. If an HTTP error occurs,
* call the specified errorHandler function, or pass null to the callback
* if no error handler is specified.
**/
HTTP.post = function(url, values, callback, errorHandler) {
var request = HTTP.newRequest();
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
callback(HTTP._getResponse(request));
}
else {
if (errorHandler) errorHandler(request.status,
request.statusText);
else callback(null);
}
}
}
request.open("POST", url);
// This header tells the server how to interpret the body of the request.
request.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
// Encode the properties of the values object and send them as
// the body of the request.
request.send(HTTP.encodeFormData(values));
};4、獲取Http頭(包括解析頭部數據)
HTTP.getHeaders = function(url, callback, errorHandler) {
var request = HTTP.newRequest();
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
callback(HTTP.parseHeaders(request));
}
else {
if (errorHandler) errorHandler(request.status,
request.statusText);
else callback(null);
}
}
}
request.open("HEAD", url);
request.send(null);
};
// Parse the response headers from an XMLHttpRequest object and return
// the header names and values as property names and values of a new object.
HTTP.parseHeaders = function(request) {
var headerText = request.getAllResponseHeaders(); // Text from the server
var headers = {}; // This will be our return value
var ls = /^"s*/; // Leading space regular expression
var ts = /"s*$/; // Trailing space regular expression
// Break the headers into lines
var lines = headerText.split(""n");
// Loop through the lines
for(var i = 0; i < lines.length; i++) {
var line = lines[i];
if (line.length == 0) continue; // Skip empty lines
// Split each line at first colon, and trim whitespace away
var pos = line.indexOf(':');
var name = line.substring(0, pos).replace(ls, "").replace(ts, "");
var value = line.substring(pos+1).replace(ls, "").replace(ts, "");
// Store the header name/value pair in a JavaScript object
headers[name] = value;
}
return headers;
};5、私有方法
1、獲取表單數據:
/**
* Encode the property name/value pairs of an object as if they were from
* an HTML form, using application/x-www-form-urlencoded format
*/
HTTP.encodeFormData = function(data) {
var pairs = [];
var regexp = /%20/g; // A regular expression to match an encoded space
for(var name in data) {
var value = data[name].toString();
// Create a name/value pair, but encode name and value first
// The global function encodeURIComponent does almost what we want,
// but it encodes spaces as %20 instead of as "+". We have to
// fix that with String.replace()
var pair = encodeURIComponent(name).replace(regexp,"+") + '=' +
encodeURIComponent(value).replace(regexp,"+");
pairs.push(pair);
}
// Concatenate all the name/value pairs, separating them with &
return pairs.join('&');
};2、獲取響應:
HTTP._getResponse = function(request) {
switch(request.getResponseHeader("Content-Type")) {
case "text/xml":
return request.responseXML;
case "text/json":
case "text/javascript":
case "application/javascript":
case "application/x-javascript":
return eval(request.responseText);
default:
return request.responseText;
}
}6、使用:
//提交表單,調用POST方法
var uname = document.getElementById("username");
var usex = document.getElementById("sex");
var formdata = {'username':'tom','sex':'男'};
HTTP.post("./test.php",formdata, doFun, errorFun);
//請求獲取指定的URL的headers
HTTP.getHeaders("./a.html", doFun, errorFun);到此這篇關于JavaScript實現異步Ajax的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
在JavaScript中使用對數Math.log()方法的教程
這篇文章主要介紹了在JavaScript中使用對數Math.log()方法的教程,是JS入門學習中的基礎知識,需要的朋友可以參考下2015-06-06
IE6瀏覽器下resize事件被執(zhí)行了多次解決方法
在IE瀏覽器下,一次resize事件被執(zhí)行了多次,這是IE6和IE7的一個比較廣為認知的問題,這個問題在這兩個版本的瀏覽器中表現有所不同,通常IE6下會比IE7下更為糟糕,接下來將介紹解決方法,需要的朋友可以參考下2012-12-12

