JavaScript的Ajax请求流程
Ajax请求的存在可以保证局部刷新页面,使得前后的交互更加完美,也减轻浏览器和服务器的符单。
书写方式
-
创建对象
var xh = new XMLHttpRequest()
做一个浏览器兼容
var xh = null; try{ xh = new XMLHttpRequest(); }catch(error){ xh = new ActiveObject("Microsoft.XMLHTTP");//IE浏览器兼容 }
-
调用open方法
xh.open(参数1,参数2,参数3)
参数1:请求方式 get post
参数2:请求url 可以是文本路径
参数3:true(异步加载)或者false(同步加载)
-
调用send方法
xh.send()
-
等待响应
xh.onreadystatechange = function(){ if(xh.readyState == 4){ if(xh.status ==200){ 处理过程; } } }
xh.readyState 发生变化的值为0,1,2,3,4
0 调用open方法的时候
1 调用send方法的之后,发送请求的时候
2 send方法完成,已经接收到所有的响应内容
3 正在解析下载的内容
4 解析完成的时候
xh.status 变化值为200,404…
200 请求过程正常,正常返回信息
404 请求页面不存在
…
post方式
var xh = new XMLHttpRequest();
xh.open('GET', url, true)//url根据实际的请求url更改
xh.send();
xh.onreadystatechange = function () {
if(xh.readyState == 4 && xh.status ==200) {
fn.call(this, xhr.responseText);
}
};
get方式
var xh = new XMLHttpRequest();
xh.open("POST", url, true);//url根据实际的请求url更改
// 添加请求头,发送信息至服务器
xh.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xh.send(data);
xh.onreadystatechange = function() {
if (xh.readyState == 4 && (xh.status == 200 || xh.status == 304)) {
fn.call(this, xhr.responseText);
}
};
封装一个万用ajax的函数
//封装一个函数,里面包含success的回调函数,error的回调函数
function $ajax({method="get", url, data, success, error}) {
let xh = null;
try{
xh = new XMLHttpRequest();//建立对象
}catch(error){
xh = new ActiveObject("Microsoft.XMLHTTP");//IE浏览器兼容
}
if(method == "get"&& data){
url += "?" + data;
}
xh.open(method,url,true);
if(method == "get"){
xh.send();//发送get请求
}else {
xh.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xh.send(data);//发送post请求
}
xh.onreadystatechange = function(){
if(xh.readyState == 4){
if(xh.status ==200){
if(success){
success();//请求成功时调用
}
}else{
if(error){
error();//请求失败时调用
}
}
}
}
}