XMLHttpRequest.response

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

XMLHttpRequestresponse 属性返回响应的正文。返回的类型为 ArrayBufferBlobDocument、JavaScript Object 或字符串中的一个。这取决于请求的 responseType 属性。

一个对象,其类型取决于 responseType 的值。你可以尝试设置 responseType 的值,以便请求特定的类型的数据。 responseType 要在调用 open() 初始化请求之后以及在调用 send() 发送请求到服务器之前设置。

如果请求尚未完成或未成功,则取值是 null。例外的,读取文本数据时如果将 responseType 的值设置成 "text" 或空字符串("")而请求状态还是 LOADING readyState(3)时,response 包含到目前为止该请求已经取得的内容。

示例

此示例提供了一个方法——load(),它可以从服务器加载和处理页面。它通过创建一个 XMLHttpRequest 对象并为 readystatechange 事件创建一个监听器。这样的话,当 readyState 变成 DONE(4)时就会获取 response 并将其传递给 load() 中提供的回调函数。

返回的内容会被作为原始文本数据处理(因为这里没有覆盖 responseType 的默认值)。

js
const url = "somePage.html"; // 一个本地页面

function load(url, callback) {
  const xhr = new XMLHttpRequest();

  xhr.onreadystatechange = () => {
    if (xhr.readyState === 4) {
      callback(xhr.response);
    }
  };

  xhr.open("GET", url, true);
  xhr.send("");
}

规范

Specification
XMLHttpRequest
# the-response-attribute

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
response

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见