ajax已有原生和jQuery的写法,jQuery的写法已经相对很简单了。但是现在还需借助promise对ajax的封装来对aja有更深入的了解。
原生写法
// get
// 发送ajax的请求
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
doResponse(xhr);
}
}
}
xhr.open('GET',`01-reg-get.php?username=${username}`,true);
xhr.send(null);
// post
var xhr = new XMLHttpRequest();
// 状态监听
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
callback(xhr);
}
}
// 3设置请求的路径
xhr.open('POST','02-add-post.php');
// 3.5 设置请求头部
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
// 4 发送post请求的参数
xhr.send('stuName=' + stuName + '&score=' + score);
}
jQuery写法
$.ajax({
url: "请求路径",
type : "请求类型",
datatype : 'jsonp', // 跨域解决
data : { // 参数
username : "cress",
password : "123456"
},
success : function(res){ // 请求成功的返回
console.log(res.data);
},
error : function(e){ // 请求失败的返回
console.log(e);
},
complete : function(){ // 不管成功与否都会执行此函数
console.log('complete');
console.log(this);
},
context : $('div'), // 改变当前环境上下文 this
timeout : 1000, // 请求的时长 在这段时间内 既没有成功也没有失败就会断开请求 但是complete还会执行
async : true // 是否异步 一般为异步
});
promise封装
首先promise会返回两种状态,正好可以模拟ajax的两种返回状态。
function getJSON(type, url, data == null) {
// 创建并返回promise
return new Promise(function(resolve, reject) {
// 创建ajax对象
let xhr = new XMLHttpRequest();
// 设置请求路径和请求参数
xhr.open(type, url, true);
// post 请求设置请求头
if(type === "POST" || type === "post"){
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
// 事件监听
xhr.onreadystatechange = function() {
if (this.readyState !== 4) return;
// 根据响应情况返回相应的promise状态
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
// 设置错误监听函数
xhr.onerror = function() {
reject(new Error(this.statusText));
};
// 设置响应的数据类型
xhr.responseType = "json";
// 发送 http 请求
xhr.send(data);
});
}