Ajax初窥
Ajax四個步驟
1. 創建Ajax對象
2. 連接到服務器
3. 發送請求
4. 接收返回值
0x01?創建AJAX對象
方法1(非IE6.0)
Var oAjax = new XMLHttpRequest();
方法2(IE6.0)
//IE6.0版本所使用的Ajax
Var oAjax = new ActiveXObject(“Micosoft.XMLHTTP”);
方法3(兼容版)
兼容的原理
//使用沒有定義的變量----報錯
//使用沒有定義的屬性----Underfine
實例代碼
<script>
Alert(a);//會提示錯誤。
Alert(window.a);//會提示underfine
</script>
那么就可以那么寫
<script>
Button.onclick = function()
{
If(window. XMLHttpRequest()){
Var oAjax = new XMLHttpRequest();
}else{
Var oAjax = new ActiveXObject(“Micosoft.XMLHTTP”);
}
}
</script>
0x02?連接服務器
Open(方法,文件名,異步傳輸)//例如:oAjax.open(‘get’,’a.txt’,true)
同步:事情一件件的來
異步:多件事情一起操作(ajax的特性就是如此)
0x03 發送請求
OAjax.send()
0x04 接收請求
oAjax.onreadstatechang=function()
{
If(oAjax.readyState == 4)//讀取完成
{
If(oAjax.status == 200){
Alert(‘成功’+oAjax.responseText);//oAjax.responseText會返回內容
}else{
Alert(‘失敗’);
}
}
}
?
總結