時(shí)下流行的Ajax并不是新技術(shù),它只是一些老技術(shù)的組合,這一點(diǎn)你可以從它的英文全稱上了解到,Ajax 是 Asynchronous JavaScript and XML(以及 DHTML 等)的縮寫,也即異步JavaScript和XML。
要了解Ajax的工作原理,下列技術(shù)必須掌握:
(1)HTML 用于建立 Web 表單并確定應(yīng)用程序其他部分使用的字段。
(2)JavaScript 代碼是運(yùn)行 Ajax 應(yīng)用程序的核心代碼,幫助改進(jìn)與服務(wù)器應(yīng)用程序的通信。
(3)DHTML 或 Dynamic HTML,用于動(dòng)態(tài)更新表單。我們將使用 div、span 和其他動(dòng)態(tài) HTML 元素來標(biāo)記 HTML。
(4)文檔對象模型 DOM 用于(通過 JavaScript 代碼)處理 HTML 結(jié)構(gòu)和(某些情況下)服務(wù)器返回的 XML。
1,Ajax中要用到的最主要的JavaScript對象是XMLHttpRequest對象,這個(gè)對象是一切應(yīng)用Ajax技術(shù)編寫代碼的最基本對象,也是最重要的對象,不同的瀏覽器下創(chuàng)建該對象的方法是不一樣的,所以在做網(wǎng)頁開發(fā)的時(shí)候必須創(chuàng)建能在通用瀏覽器上運(yùn)行的XMLHttpRequest對象,下面是創(chuàng)建該對象的代碼
<script language="javascript" type="text/javascript">
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
</script>
2,創(chuàng)建對象后,需要打開請求,一般采用get方式
var phone = document.getElementById("phone").value;
var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone);
request.open("GET", url, true);
3,指定回調(diào)方法
request.onreadystatechange = updatePage;
4,發(fā)送請求
request.send(null);
5,回調(diào)方法,處理服務(wù)器響應(yīng)
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText.split("|");
document.getElementById("order").value = response[0];
document.getElementById("address").innerHTML = response[1].replace(//g, "");
} else
alert("status is " + request.status);
}
}
最后匯總一下上面寫的JavaScript代碼
<script language="javascript" type="text/javascript">
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
function getCustomerInfo() {
var phone = document.getElementById("phone").value;
var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText.split("|");
document.getElementById("order").value = response[0];
document.getElementById("address").innerHTML = response[1].replace(//g, " ");
} else
alert("status is " + request.status);
}
}
</script>
按照上述五個(gè)步驟,就可以實(shí)現(xiàn)ajax異步傳輸?shù)木植克⑿拢浅:唵巍?/p>
轉(zhuǎn)自:http://www.cnblogs.com/gisland/