创建Ajax对象
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest(); // 标准浏览器
}else{
xhr = new ActiveXObject('Microsoft.XMLHTTP'); //早起IE浏览器
}
准备发送请求(配置发送请求的一些行为)
xhr.open(' get ', ' form.php ', true); // 其中中间参数为发送到的文件地址
执行发送的动作
xhr.send(null);
指定回调函数
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
var data = xhr.responseText; // json
// var data2 = xhr.responseXML;
}
}
}
xhr.readyState
- 0:XMLHttpRequest对象创建完成
- 1:表示发送请求的动作准备好了,但是还没开始发送
- 2:表示已经发送完成
- 3:服务器已经返回了数据
- 4:服务器返回的数据已经可以使用