核心
- 兼容写法
if(window.ActiveXObject){
ajax = new ActiveXObject(“Microsoft.XMLHTTP”);
}else if(window.XMLHttpRequest)f
ajax=new XMLHttpRequest();
- XMLHttpRequest (IE6 不兼容)
用法
创建
var ajax =new XMLHttpRequest()
打开
同步
ajax.open(“get”,"xxx.php”,false);
- 参数2:服务器地址;
- 参数3:是否异步。
ajax.open(“post”,xxx.php,false);
ajax.setRequestHeader(“Content-Type”,application/x-www-form-urlencoded”);
异步
ajax.open(“get”,"xx.php”,true)
ajax.open(“post”,xxx.php,true)
ajax.setRequestHeader(“Content-Type”,application/x-www-form-urlencoded”);
发送后状态值readystate:
0:对象已建立,还未初始化,未调用send;
1:open已调用,未调用send;
2:send已调用,其它未知 ;
3:请求已发送,正在接收数据 ;
4:表示数据已经收到。
监听
ajax.onreadystatechange=function(){
console.log(ajax.responseText)
}
发送
ajax.send(null) //发送后返回四种参数
- responseText:作为响应的主体返回的文本 ;
- responseXML;
- status :
- 200成功;
- 202请求接受,处理未完成 ;
- 400 语法错误 ;
- 404 找不到指定url;
- 500 内部服务器错误。
- statusText: 跨浏览器时可能不太一致。