如何创建ajax
1 创建一个XMLHttpRequest对象(异步调用对象
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest()
}else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
if (xhr==null) {
alert("Your browser does not support XMLHTTP.");
return;
}
2 设置onreadystatechange的回调函数
xhr.onstatechange = function(){
if(xhr.readyState === 4){
// readyState === 4 表示请求完成
if (xhr.status === 200)
// xhr.status === 200 表示相应成功
console.log(xhr.responseText)
}
}else {
// 响应失败 根据响应码判断失败原因
console.log(xhr.status)
}
}
3 创建一个新的http请求
xhr.open('get', 'test.asp')
// 第一个参数为请求方法 get或post 第二个参数为请求地址 第三个参数为true代表异步请求(默认为true,所以不用写)
4 发送请求
xhr.send();