XMLHttpRequest
- 通过XMLHttpRequest发送get请求
// 创建XMLHttpRequest实例对象
const xhr = new XMLHttpRequest();
// 监听通信状态
xhr.onreadystatechange = function(){
// 请求结束,处理服务器返回的数据
if (xhr.readyState === 4){
// http状态码为200表示成功返回
if (xhr.status === 200){
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
else {
// 显示正在加载中...
}
};
// 监听通信出错时的处理函数
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
// 添加发送请求的参数: 请求方法,url, 是否异步
xhr.open('GET', '/endpoint', true);
// 发送实际请求, GET请求参数为null
xhr.send(null);
- XMLHttpRequest对象的实例属性和方法
- readyState
0 - 表示 XMLHttpRequest 实例已经生成,但是实例的open()方法还没有被调用。
1 - 表示open()方法已经调用,但是实例的send()方法还没有调用,仍然可以使用实例的setRequestHeader()方法,设定 HTTP 请求的头信息。
2 - 表示实例的send()方法已经调用,并且服务器返回的头信息和状态码已经收到。
3 - 表示正在接收服务器传来的数据体(body 部分)。这时,如果实例的responseType属性等于text或者空字符串,responseText属性就会包含已经收到的部分信息。
4 - 表示服务器返回的数据已经完全接收,或者本次接收已经失败。
-
onreadystatechange
onreadystatechange属性指向一个监听函数。readystatechange事件发生时(实例的readyState属性变化),就会执行这个属性。 -
responseType
responseType属性是一个字符串,表示服务器返回数据的类型。这个属性是可写的,可以在调用open()方法之后、调用send()方法之前,设置这个属性的值,告诉服务器返回指定类型的数据。
XMLHttpRequest.responseType属性可以等于以下值。
""(空字符串):等同于text,表示服务器返回文本数据。
"arraybuffer":ArrayBuffer 对象,表示服务器返回二进制数组。
"blob":Blob 对象,表示服务器返回二进制对象。
"document":Document 对象,表示服务器返回一个文档对象。
"json":JSON 对象。
"text":字符串。
- response
response属性表示服务器返回的数据体(即 HTTP 回应的 body 部分)。它可能是任何数据类型,比如字符串、对象、二进制对象等等,具体的类型由XMLHttpRequest.responseType属性决定。该属性只读。
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status === 200) {
var blob = new Blob([xhr.response], {type: 'image/png'});
// 或者
var blob = xhr.response;
}
};
xhr.send();
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
var uInt8Array = new Uint8Array(this.response);
for (var i = 0, len = uInt8Array.length; i < len; ++i) {
// var byte = uInt8Array[i];
}
};
xhr.send();
- responseText
responseText属性返回从服务器接收到的字符串,该属性为只读。只有 HTTP 请求完成接收以后,该属性才会包含完整的数据。
var xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);
xhr.responseType = 'text';
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send(null);
- responseXML
responseXML属性返回从服务器接收到的 HTML 或 XML 文档对象,该属性为只读。如果本次请求没有成功,或者收到的数据不能被解析为 XML 或 HTML,该属性等于null。
var xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);
xhr.responseType = 'document';
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseXML);
}
};
xhr.send(null);