You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Fetch API获取HTML后如何刷新整个网页?

利用Fetch返回的完整HTML刷新整个网页

问题背景

假设我们通过Fetch API向服务器发送GET请求,服务器返回包含完整新网页的HTML文本。我们已掌握替换页面中div容器这类代码片段的方法,但需要知道如何利用返回的完整HTML刷新整个网页。

服务器返回的HTML示例:

<!-- html code sent by server -->
<html>
<header>
   <title>animals</title>
</header>
<body>
 <p>A spider is an animal.</p>
</body>

客户端现有代码:

//Client side
fetch('/animals')
  .then(res => res.text())
  .then(value => /*Iam missing this step*/)

解决方法

方法1:直接重写整个文档(最简便)

使用document.open()、document.write()和document.close()组合,完全替换当前页面的所有内容,效果接近页面刷新但不会触发重载事件:

fetch('/animals')
  .then(res => res.text())
  .then(html => {
    document.open();
    document.write(html);
    document.close();
  })

这个操作会清空当前文档的所有内容,写入新HTML后关闭文档流,浏览器会自动解析并渲染新页面,包括更新标题、样式和执行内嵌脚本。

方法2:替换根元素内容(支持预处理)

如果需要在渲染前对新HTML做修改,可以先解析HTML,提取关键内容后再替换:

fetch('/animals')
  .then(res => res.text())
  .then(html => {
    // 创建临时容器解析新HTML
    const tempContainer = document.createElement('div');
    tempContainer.innerHTML = html;
    
    // 单独更新页面标题(确保浏览器标签同步)
    const newTitle = tempContainer.querySelector('title');
    if (newTitle) document.title = newTitle.textContent;
    
    // 替换整个HTML根元素的内容
    document.documentElement.innerHTML = tempContainer.querySelector('html').innerHTML;
  })

这种方式可以在替换前对新HTML进行调整,比如修改某些节点后再渲染到页面。

内容的提问来源于stack exchange,提问作者KeepRunning85

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 05:12:05