发送http请求
XHR
特点:向服务器请求数据而不刷新页面
xhr发送get请求
const dom = document.querySelector(".xhrGet");
dom.addEventListener("click", xhrGet);
function xhrGet() {
const xhr = new XMLHttpRequest(); // 创建一个XHR对象
xhr.onreadystatechange = function () { // 监听xhr对象的readyState
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
console.log(xhr.responseText);
} else {
console.log("request fail");
}
}
};
// 请求方法及地址,可选参数布尔值--表示是否异步
xhr.open("get", "http://localhost:8080/api/contactList");
xhr.send(null); // 请求体的数据,没有则为null
}
xhr发送post请求
const btn = document.querySelector(".xhrPost");
btn.addEventListener("click", xhrPost, false);
function xhrPost() {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
console.log(xhr.responseText);
} else {
console.log("request fail");
}
}
};
xhr.open("post", "http://localhost:8080/api/contact/new/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(
JSON.stringify({
name: "钢弹",
tel: 15025455666,
})
);
}
xhr的方法
// 终止当前请求
xhr.abort()
// 设置请求头信息
xhr.setRequestHeader("Content-Type","application/json")
xhr事件**
timeout事件
如果发送请求后8秒,响应不成功,那么请求会中断,触发timeout的事件处理程序;readystate会变为4;仍然会调用onreadystatechagne事件处理程序,但是此时访问status会报错,所以最好把status放在try/catch中
xhr.timeout = 8000;
xhr.addEventListener("timeout", function () {
console.log("require fail,timeout");
});
error事件
请求发生错误时触发
xhr.addEventListener("error", function () {
console.log("require error");
});
abort事件
当请求中断时调用事件处理程序,比如请求超时,或者自己调用abort方法
xhr.addEventListener("abort", function () {
console.log("require aborted");
});
readystatechange事件
前面例子中使用过了
readyState的值及含义:
0:尚未初始化,未调用open
1: 已调用open,但没调用send
2: 已发送(已经调用send),未收到响应
3: 接受中,已接到vu分响应
4: 响应接收完成
load事件
作用和readystatechagne事件一样,相当于是它的一个替代品,ie9开始支持
xhr.addEventListener("load", function () {
console.log("get response");
});
Fetch
特点:基于Promise设计,更加语义化,好理解
fetch发送get请求
const fetchGetBtn = document.querySelector(".fetchGet");
fetchGetBtn.addEventListener("click", fetchGet);
function fetchGet() {
fetch("http://localhost:8080/api/contactList").then((res) => {
res.text().then((data) => {
console.log(data);
});
});
}
fetch发送post请求
const fetchPostBtm = document.querySelector(".fetchPost");
fetchPostBtm.addEventListener("click", fetchPost);
function fetchPost() {
fetch("http://localhost:8080/api/contact/new/json", {
method: "POST",
body: JSON.stringify({ name: "ghost", tel: 11044444444 }),
headers: new Headers({ "Content-Type": "application/json" }),
}).then((res) => {
res.text().then((data) => console.log(data));
});
}
fetch相比于xhr
优点:基于promise,支持async/await; fetch的语法简洁,更语义化
缺点:
- fetch只对网络错误报错,http状态码错误不报错
- fetch不支持abort,无法终止
- fetch不支持超时控制,使用setTimeout和Promise.reject实现的超时控制不能阻止请求过程继续在后台运行,造成了流量的浪费
- fetch没有原生检测请求进度的方式,XHR可以
- 默认情况下fetch不发送cookie,除非手动配置