定义:
XHR对象用于与服务器交互。
可以在不刷新页面的情况下请求特定 URL,获取数据。
可以用于获取任何类型的数据,而不仅仅是 XML。
支持 HTTP 以外的协议(包括 file:// 和 FTP)。
主要函数:
1. open
语法:
xhrReq.open(method, url);
xhrReq.open(method, url, async);
xhrReq.open(method, url, async, user);
xhrReq.open(method, url, async, user, password);
参数:
method:
POST/GET/PUT/DELETE
async:
是否异步,默认true
2. setRequestHeader
语法:
xhrReq.setRequestHeader(header, value);
注意:
1. 此方法必须在open()方法和send()之间调用
2. 多次对同一个请求头赋值,只会生成一个合并了多个值的请求头。
3. 如果没有设置 Accept 属性,则此发送出send() 的值为此属性的默认值*/*
3. send
语法:
xhrReq.send(body)
参数:
body:
在XHR请求中要发送的数据体
可以是 Blob, BufferSource, FormData, URLSearchParams, 或者 USVString 对象.
没有指定值,则默认值为 null
4. onload 请求成功时回调
xhrReq.onload = e => {...}
5. onloaded 请求结束时回调,不论是否成功
xhrReq.onloaded = e => {...}
6. onerror 请求出错时回调
xhrReq.onerror = e => {...}
7. ontimeout 请求超时时回调
xhrReq.ontimeout = e => {...}
8. onreadystatechange
说明:
在 XMLHttpRequest 的readyState 属性发生改变时触发 readystatechange 事件的时候被调用。
语法:
xhrReq.onreadystatechange = e => {...};
注意:
该方法不用于同步的requests对象
9. readyState
请求的状态,5个值;
0:为初始化,1:正在加载;2:已经加载,3:交互中,4:完成
10. responseText 服务器的响应,表示为字符串
11. responseXML 服务器的响应,表示为XML,可以解析为DOM对象
12. status 服务器的HTTP状态码
200:ok,304:not modified,404:Not Found
13. statusText Http 状态码的相应文本
ok 或 Not Found
// get 请求
let xhr = new XMLHttpRequest;
let url = "http://api.apishop.net/common/postcode/getAddrs?apiKey=HIygaGm1a505fa909bf098d92ae591208f75a77fccf1e63";
xhr.open('GET', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.status === 200) {
alert(200);
} else {
alert(xhr.statusText);
}
}
// post 请求 send(params)
let xhr = new XMLHttpRequest;
let url = "http://api.apishop.net/common/postcode/getAddrs";
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('apiKey=HIygaGm1a505fa909bf098d92ae591208f75a77fccf1e63');
xhr.onreadystatechange = function () {
if (xhr.status === 200) {
alert(200);
} else {
alert(xhr.statusText);
}
}
// post 请求 new FormData => send(formData)
let xhr = new XMLHttpRequest;
let url = "http://api.apishop.net/common/postcode/getAddrs";
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
let fd = new FormData();
fd.append("apiKey", "HIygaGm1a505fa909bf098d92ae591208f75a77fccf1e63")
xhr.send(fd);
xhr.onreadystatechange = function () {
if (xhr.status === 200) {
alert(200);
} else {
alert(xhr.statusText);
}
}
// post 请求 JSON => send(json)
let xhr = new XMLHttpRequest;
let url = "http://api.apishop.net/common/postcode/getAddrs";
xhr.open('POST', url, true);
let fd = {
"apiKey": "HIygaGm1a505fa909bf098d92ae591208f75a77fccf1e63"
}
xhr.send(JSON.stringify(fd));
xhr.onreadystatechange = function () {
if (xhr.status === 200) {
alert(200);
} else {
alert(xhr.statusText);
}
}