https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
var onSuccess = function(result){
}; //成功的回调
var onFail = function(error){
}; //失败的回调
var req = new XMLHttpRequest();
req.open("POST", "www.baidu.com", true); // true 是否异步
req.onload = function(){
if(req.readyState === 4 && req.status === 200){
onSuccess(req.response);
} else {
onFail(req.statusText);
}
}
req.onerror = function(){
onFail(Error("网络异常"));
}
function ajaxPrpmise () {
let promise = new Promise( (resolve,reject) => {
let xhr = new XMLHttpRequest();
xhr.open('get',''xx.gif',true)
xhr.onreadystatechange = () =>{
if( xhr.readyState === 4 ){
if(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304 ){
resolve( xhr.responseURL)
} else {
reject( new Error(xhr.statusText))
}
}
}
xhr.send(null)
} )
return promise
}
参考: https://www.bilibili.com/video/BV1jv411P7Hp/?spm_id_from=333.788
const ajax = url => {
return new Promise((resolve, reject) => {
let req = new XMLHttpRequest();
req.open("POST", url, true);
req.onload = () => {
if(req.readyState === 4 && req.status === 200){
resolve(req.response);
} else {
reject(req.statusText);
}
}
req.onerror = () => {
reject(Error("网络异常"));
}
})
}