AJAX操作主要分為如下幾步:
1.創(chuàng)建 XMLHttpRequest 對象
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");
}
2.向服務器發(fā)送請求
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
方法描述:
open(method,url,async)規(guī)定請求的類型、URL 以及是否異步處理請求采郎。
method:請求的類型;GET 或 POST
url:文件在服務器上的位置
async:true(異步)或 false(同步)
send(string)將請求發(fā)送到服務器畜伐。
string:僅用于 POST 請求
向服務器傳遞參數(shù):
//GET:
xmlhttp.open("GET","demo_get2.asp?fname=Bill&lname=Gates",true);
xmlhttp.send();
//POST:
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
3.執(zhí)行函數(shù)
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}