1.创建对象
var xhr = null // ajax请求
try{
xhr = new XMLHttpRequest() // IE8以下不支持
}catch(error){
xhr = new ActiveXObject("Microsoft.XMLHTTP")// IE8以下支持,处理兼容问题
}
2.初始化
如果使用get方法,发送的数据要放在url地址后面
xhr.open('get','1.php?name="zhangsan"&age=18',true)
//第一参数 get 还是 post
//参数二 url 1.php
//参数三 false同步 还是 true异步
xhr.open('post','1.php')
//如果使用post方法需要设置请求头信息,发送的数据放在send方法的参数里
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
3.发送
xhr.send('name="zhangsan"&age=18');
4.响应数据
xhr.onreadystatechange=function(){
if(xhr.readyState == 4){
请求的状态 readyState
0:请求未初始化
1:服务器连接已经建立
2:请求已经接收
3:服务器处理请求
4:服务器处理结束,返回结果
XMLHttpRequest对象请求状态为4的时候,代表请求成功
if(xhr.status ==200){
//status状态码 200代表请求成功。一般用于GET与POST请求
//404代表没有找到页面
console.log(xhr.response)
}
}
}