Ajax请求的五个步骤
① 创建XMLHttpRequest异步对象
var xmlHttp = new XmlHttpRequest();
② 设置回调函数
#onreadystatechange :存储函数。每当readyState属性改变时就会调用函数
xmlHttp.onreadystatechange = fn();
③ 使用open方法与服务器建立连接
#open方法
open(method,url,async);
method:请求的类型 GET或POST
url:文件在服务器上的路径
async:true(异步)或false(同步)
#get请求
xmlHttp.open("get","/WEB11/js_ajax","true");
#post请求,需要设置请求头
xmlHttp.open("get","/WEB11/js_ajax","true");
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
④ 使用send方法提交请求
#get 不需要传递参数
xmlHttp.send(null);
#post 需要传递参数
xmlHttp.send("name=mufeng&age=18");
⑤ 在回调函数中针对不同的响应状态进行处理
#readyState:存有XMLHttpRequest的状态。从 0 到 4 发生变化;
0:请求未初始化
1:服务器连接已建立
2:请求已接收
3:请求处理中
4:请求已完成,且响应已经就绪
#status
200:"OK"
404: "未找到页面"
function fn(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var res = xhr.responseText
res = JSON.parse(res)
}
}