XMLHttpRequest
XMLHttpRequest
基础使用
open(
method, // 请求的方式,如 GET/POST/HEADER 等,这个参数不区分大小写
url // 请求的地址,可以是相对地址或者绝对地址
[, async = true // 默认值为true,即为异步请求,若async=false,则为同步请求
[, username = null // Basic 认证的用户名密码
[, password = null]]]
);
值得一提的是,第三个参数
const xhr = new XMLHttpRequest();
xhr.timeout = 3000;
xhr.ontimeout = function(event) {
alert("请求超时!");
};
const formData = new FormData();
formData.append("tel", "18217767969");
formData.append("psw", "111111");
xhr.open("POST", "http://www.test.com:8000/login");
xhr.send(formData);
// 如果是同步请求,则不需要监听事件
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert(xhr.statusText);
}
};
对于部分老版本浏览器,我们还需要考虑兼容性问题,即判断是否存在
// Just getting XHR is a mess!
if (window.XMLHttpRequest) {
// Mozilla, Safari, ...
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
// Open, send.
request.open("GET", "https://davidwalsh.name/ajax-endpoint", true);
request.send(null);
下表列举了
属性 | 类型 | 描述 |
---|---|---|
onreadystatechange |
Function? |
一个 |
readyState |
unsigned short |
请求的五种状态值状态描述0``UNSENT open() 方法还未被调用1``OPENED send() 方法还未被调用2``HEADERS_RECEIVED (已获取响应头)``send() 方法已经被调用3``LOADING (正在下载响应体) 响应体下载中responseText 中已经获取了部分数据4``DONE (请求完成) 整个请求过程已经完毕 |
response |
consties | 响应实体的类型由 responseType 来指定, 可以是 ArrayBuffer, Blob, Document ,null。 |
responseText |
DOMString |
此次请求的响应为文本,或是当请求未成功或还未发送时为 null。 只读。 |
responseType |
XMLHttpRequestResponseType |
设置该值能够改变响应类型。就是告诉服务器你期望的响应格式。response "" "arraybuffer" ArrayBuffer "blob" Blob "document" Document "json" "text" 字符串 |
responseXML |
Document? |
本次请求的响应是一个 Document 对象,如果是以下情况则值为 null: 请求未成功,请求未发送,或响应无法被解析成responseType 设置为text/html 流来解析。只读text/xml overrideMimeType() 强制 ``XMLHttpRequest 将响应解析为 |
status |
unsigned short |
该请求的响应状态码状态码 |
statusText |
DOMString |
该请求的响应状态信息200 OK ” |
upload |
XMLHttpRequestUpload |
可以在 upload 上添加一个事件监听来跟踪上传过程。 |
withCredentials |
boolean |
表明在进行跨站false。 注意 |