js原生xhr请求XMLHttpRequest
创建一个请求实例,发送请求
var xhr = new XMLHttpRequest(); xhr.open('GET', 'test.php'); xhr.send();
监控XMLHttpRequest对象的状态变化
xhr.onreadystatechange = function(){ if ( xhr.readyState == 4 && xhr.status == 200 ) { console.log( xhr.responseText ); } else { console.log( xhr.statusText ); } };
请求时限
xhr.timeout = 3000; xhr.ontimeout = function(event){ alert('请求超时!'); }
FormData对象
var formData = new FormData(); formData.append('aa', '12'); xhr.open('POST', url); xhr.send(formData);
接收二进制数据
xhr.responseType = 'blob'; var blob = new Blob([xhr.response]);
进度信息
xhr.onprogress = function updateProgress(event) { if (event.lengthComputable) { var percentComplete = event.loaded / event.total; } }
其它回调
xhr.onloadstart = function () { console.log("传输开始", 1); }; xhr.onload = function () { console.log("传输完成", 2); }; xhr.onloadend = function () { console.log("传输结束", 3); }; xhr.onabort = function () { console.log("用户取消"); }; xhr.onerror = function () { console.log("error"); };
获取响应头信息
#获取指定响应头 xhr.getResponseHeader("content-disposition") #获取所有响应头,字符串格式 var headers = xhr.getAllResponseHeaders().toLowerCase();