XMLHttpRequest: responseText 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

注意:此功能在 Web Workers 中可用,但 Service Workers 除外。

只读的 XMLHttpRequest 属性 responseText 返回发送请求后从服务器接收到的文本。

一个字符串,包含使用 XMLHttpRequest 接收到的文本数据,如果请求失败或尚未收到任何内容,则为空字符串 ""

在处理异步请求时,responseText 的值始终包含从服务器接收到的当前内容,即使由于数据尚未完全接收而导致其不完整。

readyState 的值为 XMLHttpRequest.DONE (4) 且 status 的值为 200 ("OK") 时,您就知道已收到全部内容。

异常

InvalidStateError DOMException

如果 XMLHttpRequest.responseType 未设置为空字符串或 "text",则会抛出此异常。由于 responseText 属性仅对文本内容有效,任何其他值都表示错误条件。

示例

js
const xhr = new XMLHttpRequest();
xhr.open("GET", "/server", true);

// If specified, responseType must be empty string or "text"
xhr.responseType = "text";

xhr.onload = () => {
  if (xhr.readyState === xhr.DONE) {
    if (xhr.status === 200) {
      console.log(xhr.response);
      console.log(xhr.responseText);
    }
  }
};

xhr.send(null);

规范

规范
XMLHttpRequest
# the-responsetext-attribute

浏览器兼容性