【问题标题】:Can fetch() do responseType=document?fetch() 可以做 responseType=document 吗?
【发布时间】:2018-01-12 16:55:28
【问题描述】:

XHR 的 responseType='document' 非常棒,因为它会将一个 DOM 文档交还给您,您可以在其中使用 querySelector 等:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/', true);
xhr.responseType = 'document';
xhr.onload = function(e) {
  var document = e.target.response;
  var h2headings = document.querySelectorAll('h2');
  // ...
};

fetch 方法可以做到这一点吗?

【问题讨论】:

    标签: xmlhttprequest fetch-api


    【解决方案1】:

    fetch 本身不支持它,因为该 API 是一个纯粹的网络层 API,不依赖于 Web 浏览器 (see discussion),但实现起来并不难:

    fetch('/').then(res => res.text())
      .then(text => new DOMParser().parseFromString(text, 'text/html'))
      .then(document => {
        const h2headings = document.querySelectorAll('h2');
        // ...
      });
    

    【讨论】:

    • 手动使用 DOMParser 与原生 XHR 方式有区别吗? XHR 是在另一个线程上做的吗,比如 HTMLParserThread 并通过 DOMParser 做会在主 UI 线程或任何其他线程上做吗?
    • @prateekbh 不,这些是等价的。相同的线程。语义相同。下面是 XHR 的 responseType 文档的 impl:cs.chromium.org/chromium/src/third_party/blink/renderer/core/… .. 两者的实现看起来是一样的。
    • 假设响应是 HTML 文档,XHR 能够解析 XML/SVG 文档,仅基于 responseType 标头。
    猜你喜欢
    • 2012-02-14
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 2020-07-09
    • 2013-01-28
    相关资源
    最近更新 更多