Ajax初窥

时间:2023-03-09 19:13:23
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(‘失败’);
}
}
}