原生ajax的封装使用
我们先准备一个服务器
- server.js
const express = require("express")
const app = express()
app.get("/user",(req,res)=>{
// res.setHeader("Access-Control-Allow-Methods","*")
res.setHeader('Access-Control-Allow-Origin','*')
console.log("服务器收到请求");
res.send({"name":"hello","age":20})
})
app.listen(8080,()=>{
console.log("服务器启动,监听8080端口!");
})
启动服务器:node server.js
最基本的封装
<div>
<button onclick="sendMessage()">发送请求</button>
</div>
<script>
// 点击触发sendMessage()方法
function sendMessage(){
// 调用封装的ajax方法,传入url,回调函数
getData("http://localhost:8080/user",(res)=>{
console.log(res);
})
}
/**
* @function 封装ajax
* @url:请求的url地址
* @callback,请求成功后的回调函数
*/
function getData(url,callback){
let xhr = new XMLHttpRequest()
xhr.open("get",url)
xhr.send()
xhr.responseType = "json" // 返回response对象
xhr.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
// console.log(xhr.response);
callback(xhr.response) // 回调函数
}
}
}
</script>
ES6中的promise函数封装
- 纯pormise实现
<script>
// 点击触发sendMessage()方法
function sendMessage() {
// 调用封装的ajax方法,传入url,回调函数
getData("http://localhost:8080/user", (res) => {
console.log(res);
});
}
/**
* @url:请求的url地址
* @callback,请求成功后的回调函数
*/
function getData(url, callback) {
const p = new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open("get", url);
xhr.send();
xhr.responseType = "json"; // 返回response对象
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
// 成功则获取响应体
resolve(xhr.response);
} else {
// 失败就返回状态码
reject(xhr.status);
}
}
};
});
p.then(
function (value) {
callback(value); // value就是xhr.response
},
function (err) {
console.log(err);
}
);
}
</script>
- promise+async+await实现
<div>
<button onclick="sendMessage()">发送请求</button>
</div>
<script>
// 点击触发sendMessage()方法
async function sendMessage() {
// 调用封装的ajax方法,传入url,回调函数
let result = await getData("http://localhost:8080/user");
console.log(result);
}
/**
* @url:请求的url地址
*/
function getData(url) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open("get", url);
xhr.send();
xhr.responseType = "json"; // 返回response对象
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
// 成功则获取响应体
resolve(xhr.response);
} else {
// 失败就返回状态码
reject(xhr.status);
}
}
};
});
}
</script>