XMLHttpRequest
示例
function ajax () {
var formData = new FormData();
formData.append('name', 'zhangsan');
// 创建 xhr
var xhr = new XMLHttpRequest();
// 设置超时
xhr.timeout = 3000;
// 返回格式
xhr.responseType = 'text';
// 发送异步请求
xhr.open('POST', 'http://127.0.0.1:3000/api', true);
// 设置请求头
xhr.setRequestHeader('X-Token', 'one1');
xhr.setRequestHeader('X-Token', 'one2'); // 不会覆盖,而是追加append
// 回调
xhr.onload = function (e) {
if (this.status == 200 || this.status == 304) {
console.log(this.responseText);
}
}
xhr.ontimeout = function (e) {};
xhr.onerror = function (e) {};
xhr.upload.onpregress = function (e){};
// 发送
xhr.send(formData);
}获取response header
指定xhr.response的数据类型
xhr.response的数据类型获取response数据
请求状态
设置请求超时
同步请求
上传/下载速度
xhr.withCredentials与CORS
xhr.withCredentials与CORSxhr 事件
xhr 事件参考
Last updated