将一个promise对象放在某个常量中,在promise对象里调用 XMLHttpRequest
- 原生js写法
const ajaxPromise = function (params) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(params.type || "get", params.url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=utf-8')
xhr.send(JSON.stringify(params.data) || null);
xhr.onreadystatechange = () => {
if (xhr.readyState===4 && xhr.status===200) {
resolve(JSON.parse(xhr.responseText));
}
}
})
}
- jQurey写法
const ajaxPromise = function (params) {
const _token = '你的token'
const _contentType = 'application/json;charset=UTF-8'
return new Promise((resolve,reject) => {
$.ajax({
url: params.url,
type: params.type || 'get',
data: params.data,
// 如果需要携带本地cookie信息
xhrFields: {
withCredentials: true,
},
// 跨域请求
crossDomain: true,
// 发送ajax请求之前向http的head里面加入验证信息
beforeSend: function (xhr) {
// 携带token
xhr.setRequestHeader('token', _token)
// 携带Content-Type资源的MIME类型
xhr.setRequestHeader('Content-Type', _contentType)
},
// 请求成功后返回值,data:返回的数据,status:状态,xhr:服务器响应的数据
success: (data, status, xhr) => {
resolve(JSON.parse(data))
},
error: (error) => {
reject(err)
}
})
})
}
版权声明:本文为xjtarzan原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。