js-challenges
js-challenges copied to clipboard
使用Promise封装AJAX请求
function getJson(url){
let promise = new Promise((resolve,reject)=>{
let xhr = new XMLHttpRequest()
//创建一个http请求
xhr.open('Get',url,true)
xhr.onreadystatechange=function(){
if(this.readyState!==4)return
if(this.status>=200&&this.status<400){
resolve(this.response)
}else{
reject(new Error(this.statusText))
}
}
//设置错误监听函数
xhr.onerror=function(){
reject(new Error(this.statusText))
}
//设置响应数据类型
xhr.setRequestHeader('Accept',"application/json")
//发送http请求
xhr.send(null)
})
return promise
}
function requestData(url, method, ...args) {
return new Promise((res, rej) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.send();
xhr.onload = () => {
console.log(xhr);
if (xhr.status !== 200) {
console.log(11111);
rej(new Error(`响应码${xhr.status}`));
} else {
res(xhr.response);
}
};
});
}
requestData(url, "get")
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
function myajax(url, method) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.send(null);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(xhr.response);
} else {
reject("error");
}
}
};
});
}
function asyncAjax(way, url, params) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
if (way === "get") {
let param_list = [];
for (let key of Object.keys(params)) {
param_list.push(key + "=" + params[key]);
}
if (param_list.length !== 0) {
let param_str = param_list.join("&");
url += "?" + param_str;
}
xhr.open(way, url);
xhr.send();
} else {
xhr.open(way, url);
xhr.sendRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(params))
}
xhr.onload = function(){
if(this.status >= 200 && this.status <= 400) {
resolve(this.response);
}else {
reject(new Error(this.statusText));
}
};
xhr.onerror = function(){
reject(this.statusText);
}
})
}
function ajaxPromise(url, method, data) {
return new Promise((resolve, reject) => {
// 1.创建XMLHttpRequest对象
const xhr = new XMLHttpRequest();
// 2.与服务器建立连接
xhr.open(method, url, true);
// 3.给服务器发送数据
xhr.send(method === "POST" && data ? JSON.stringify(data) : null);
// 4.接收请求
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 300) {
resolve(JSON.parse(this.responseText));
} else {
reject(this.status);
}
}
});
});
}
ajaxPromise("GET", "https://dog.ceo/api/breeds/image/random")
.then((res) => {
console.log(res);
})
.catch((err) => {
console.error(err);
});
function axios(url, methods, ops) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); // 1. xhr.open(methods, url); // 设置请求头 xhr.setRequestHeader("a", 10); // 2. xhr.send({ b: 1 }); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.readyState === 200) { resolve(xhr.response); } else { reject("出问题了哦"); } } }; });
function myAjax(url,options){
const xhr = new XMLHttpRequest()
return new Promise((resolve,reject) => {
xhr.onload = function(...args){
console.log(args)
resolve()
}
xhr.onerror = function(...args){
console.log(args)
reject(new Error('请求失败'))
}
xhr.open(options.method,url)
xhr.send(options.body)
})
}