设置XMLHttpRequest请求链接返回数据类型XML显示null?

需要请求链接,获取返回数据中元素的值,比如<a>https://x</a>

xhr.responseText能正常显示,但是不能遍历元素

设置返回结果类型为JSON,提示错误

在百度首页控制台,请求百度个人信息页面,返回类型为xml,显示为null:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'my/index/', true);

// 如果已指明,responseType 必须是空字符串或 "document"
xhr.responseType = 'document';

// overrideMimeType() 用来强制解析 response 为 XML
xhr.overrideMimeType('text/xml');

xhr.onload = function () {
  if (xhr.readyState === xhr.DONE) {
    if (xhr.status === 200) {
      console.log(xhr.responseXML);
    }
  }
};

xhr.send(null);
阅读 3.8k
1 个回答

该请求返回的文本格式是 HTML,并不能由 XML 解析器正确地解析。解析失败时就返回 null。

  1. Otherwise, let document be a document that represents the result of running the XML parser with XML scripting support disabled on xhr’s received bytes. If that fails (unsupported character encoding, namespace well-formedness error, etc.), then return null.

—— set a document response | XMLHttpRequest Standard

你可以选择不使用 overrideMimeType,或者是 override 为 text/htmltext/html; charset=utf-8 之类,以 HTML Document 的形式解析。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题