Requête AJAX encapsulée à l'aide de Promise
function p(method="GET", url, data=null){
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onreadystatechange = function() {
if(xhr.status === 200 && xhr.readyState === 4){
resolve(xhr.responseText);
} else {
reject(xhr.responseText);
}
}
xhr.send(data);
})
}
p("GET", "请求地址", data)
.then(res => {
console.log(res);
return request('请求地址2')
}).then((res)=>{
console.log(res);
})
Requête $ .ajax encapsulée à l'aide de Promise
function p(url, type="GET", data=null) {
return new Promise((resolve, reject) => {
$.ajax({
url, type, data,
success(res) {
resolve(res)
},
error(res) {
reject(res)
}
})
})
}
p('请求地址1',"GET",data).then((res) => {
console.log(res)
return request('请求地址2')
}).then((res) => {
console.log(res)
})
Utiliser la demande de récupération encapsulée Promise
class EasyHttp {
get(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err))
})
}
post(url, data) {
return new Promise((resolve, reject) => {
fetch(url, {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err))
})
}
put(url, data) {
return new Promise((resolve, reject) => {
fetch(url, {
method: "PUT",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err))
})
}
delete(url) {
return new Promise((resolve, reject) => {
fetch(url, {
method: "DELETE",
headers: {
'Content-type': 'application/json'
}
})
.then(res => res.json())
.then(data => resolve('数据删除成功!'))
.catch(err => reject(err))
})
}
}
class EasyHttp {
async get(url) {
const response = await fetch(url);
const resData = await response.json();
return resData;
}
async post(url, data) {
const response = await fetch(url, {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(data)
});
const resData = await response.json();
return resData;
}
async put(url, data) {
const response = await fetch(url, {
method: "PUT",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(data)
});
const resData = await response.json();
return resData;
}
async delete(url) {
const response = await fetch(url, {
method: "DELETE",
headers: {
'Content-type': 'application/json'
}
})
const resData = await "数据删除成功!";
return resData;
}
}