网络请求
XHR
使用步骤:
- 创建xhr实例对象
- 调用open方法 ,参数分别是(请求类型,请求RUL,是否异步请求)。此方法为做好请求准备。
- 调用send方法,发送请求。参数为请求实体,如果没有,则传入null。
js
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText);
} else {
console.log(xhr.status);
}
}
};
xhr.open("get", "http://localhost:8000/moment/22", false);
xhr.send(null);
相应信息:
- responseText : 作为响应题返回的文本。
- status:响应的http的状态
- statusText:响应的http状态描述。
异步请求下,我们可以通过readyState来监听xhr的状态
- 0 :未初始化,尚未调用open()
- 1 :已调用open(),尚未调用send()
- 2 :已发送,已调用send(),尚未收到响应。
- 3 :接受中,已经收到部分响应。
- 4 : 已经收到所有响应。
xhr.abort()
:在收到响应之前,如果要取消异步请求,可以调用xhr.abort( )方法。
Http头部
- Accept:浏览器可以处理的内容类型。
- Accept-Charset:浏览器可以显示的字符集。
- Accept-Encoding:浏览器可以处理的压缩编码类型。
- Accept-Language:浏览器使用的语言。
- Connection:浏览器与服务器的连接类型。
- Cookie:页面中设置的Cookie。
- Host:发送请求的页面所在的域。
- Referer:发送请求的页面的URI。
- User-Agent:浏览器的用户代理字符串。
可以通过xhr.setRequestHeader()
的自定义头部字段。
js
xhr.setRequestHeader("myheader", "headervalue");
xhr.getResponseHeader()
获取相应头部信息。
js
console.log(xhr.getAllResponseHeaders());
post请求:
js
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText);
console.log(xhr.getAllResponseHeaders());
} else {
console.log(xhr.status);
}
}
};
xhr.open("post", "http://localhost:8000/login", false);
//设置携带的数据格式
xhr.setRequestHeader("Content-Type", "application/json");
const json = JSON.stringify({
name: "long",
password: 123456,
});
xhr.send(json);
FormData类型
对表单内容序列化,向服务器发送请求。
js
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText);
console.log(xhr.getAllResponseHeaders());
} else {
console.log(xhr.status);
}
}
};
xhr.open("post", "http://localhost:8000", false);
// xhr.setRequestHeader("Content-Type", "application/json");
const json = JSON.stringify({
name: "long",
password: 123456,
});
let info = document.getElementById("user-info");
//也可以自定义表单内容,append方法向添加表单属性和值。
// let data = new FormData();
// data.append("name", "wang");
xhr.send(new FormData(info));
teimout:设置请求超时时间
ontimeout监听超时时间,如果超时,执行函数。
js
xhr.open("post", "http://localhost:8000", true);
xhr.timeout = 1000;
xhr.ontimeout = function () {
alert("request fail");
};
xhr.send(new FormData(info));