1. 第一步(得到XMLHttpRequest)
*Ajax其實只需要學習一個對象:XMLHttpRequest,如果掌握了 它,就掌握了Ajax。
*得到XMLHttpRequest
===>大多數瀏覽器支持:var xmlHttp = new XMLHttpRequest();
===>IE6.0:var xmlHttp = new ActiveXObject(“Msxm12.XMLHTTP”);
===>IE5.5:var xmlHttp =new ActiveXObject(“Microsoft.XMLHTTP”);
*編寫創建XmlHttpRequest(異步對象)對象的函數
function createXMLHttpRequest()
{
try{
return new XMLHttpRequest();
}
catch(e){
try{
return new ActiveXObject("Msxm12.XMLHTTP");
}
catch(e){
try{
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){throw e;}
}
}
}
2.第二步(打開與服務器的連接)
*xmlHttp.open():用來打開與服務器的連接,它需要三個參數:
===>請求方式:可以是GET或POST
===>請求的URL:指定服務端資源:例如/Demo/AServlet
===>請求是否爲異步:如果爲true代表發送異步請求,否則同步請求。
eg:
xmlHttp.open("GET","/Demo/AServlet",true);
xmlHttp.open("POST","/Demo/AServlet",true);
3.第三步(發送請求)
*xmlHttp.send(null):如果不給null可能會造成部分瀏覽器無法發送!
===>參數:就是請求體內容!如果是GET請求,必須給出null。
如果發送時帶有參數一般使用post請求
===>如果是POST請求
1.設置Content-Type請求頭:
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
2.send:
xmlHttp("username=zhangSan&password=123")
4.第四步(得到響應)
*在xmlHttp對象的一個事件上註冊監聽器:onreadystatechange
*xmlHttp對象一共有5個狀態:
===>0狀態:剛創建xmHttp對象,還沒有調用open()方法;
===>1狀態:請求開始,還沒有調用send()方法;
===>2狀態:調用完了send()方法;
===>3狀態:服務器開始響應,但不表示響應結束;
===>4狀態:服務器響應結束;(通常我們只關心這個狀態!)
*得到xmlHttp對象的狀態:
==>
//state可能是0,1,2,3,4
var stata = xmlHttp.readyState;
*得到服務器響應的狀態碼:
==>
//例如爲200,404,500
var stata = xmlHttp.status;
*得到服務器響應的內容:
==>
//得到服務器響應的文本格式的內容
var content = xmlHttp.responseText;
//得到服務器響應的xml響應的內容,它是Document對象
var content = xmlHttp.responseXML;
示例:
//當狀態改變時會調用該方法
xmlHttp.onreadystatchange = function()
{
//雙重判斷:判斷是否爲4狀態,而且還要判斷是否爲200
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
//獲取服務器的響應內容
var text = xmlHttp.responseText;
}
}
DEMO
//對於不同的瀏覽器 創建不同的XMLHttpRequest對象
function createHttpRequest()
{
try{
return new XMLHttpRequest();
}
catch(e)
{
try{
return new ActiveXObject("Msxm12.XMLHTTP");
}
catch(e){
try{
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
alert("上古瀏覽器吧你!");
throw e;}
}
}
}
/*
*
* object的參數
* method-->可選
* url
* async-->可選
* params-->可選
* type-->可選
* callback
* Object是一個json
*/
//調用該方法時需要創建一個json對象來進行調用
function ajax(object)
{
var xmlHttp=createHttpRequest();
if(object.method==undefined)
{
object.method="GET";
}
if(object.async==undefined)
{
object.async=true;
}
xmlHttp.open(object.method, object.url, object.async);
if(object.method=="POST")
{
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
}
xmlHttp.send(object.params);
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4&&xmlHttp.status==200)
{
var data;
if(object.type==undefined)
{
data=xmlHttp.responseText;
}
else if(object.type=="text")
{
data=xmlHttp.responseText;
}
else if(object.type=="json")
{
data=eval("("+xmlHttp.responseText+")");
}
else if(object.type=="xml")
{
data=xmlHttp.responseXML;
}
object.callback(data);
}
};
}