gpt4 book ai didi

javascript - 我如何使用 fetch api 用它的 javascript 加载 html 页面?

转载 作者:行者123 更新时间:2023-12-05 00:35:40 24 4
gpt4 key购买 nike

我正在尝试使用 fetch API 加载带有其 JavaScript 脚本的 HTML 页面

我可以使用 ajax 和 JQuery See here加载页面但是,可以使用 fetch API 吗?

这是一个代码演示:

我假设你在 localhost 上运行它

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>fetch API</title>
</head>
<body>
<p>index page</p>
<div id="content">

</div>

<script>
fetch('./page.html')
.then(data => data.text())
.then(html => document.getElementById('content').innerHTML = html);
</script>
</body>
</html>


要加载的页面:
<!-- page.html -->
<p> i am the loaded page</p>
<script type="text/javascript">
alert("Javascript is working");
</script>


The <p> tag I am the loaded page will run but the <script> wont alert or any kind of JavaScript

最佳答案

请引用 stackoverflow用于将脚本插入 innerhtml 。

我已经完成了 index.html 的更改,它对我有用。请在下面找到代码

  fetch('./page.html')
.then(function (data) {
return data.text();
})
.then(function (html) {
document.getElementById('content').innerHTML = html;
var scripts = document.getElementById("content").querySelectorAll("script");
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].innerText) {
eval(scripts[i].innerText);
} else {
fetch(scripts[i].src).then(function (data) {
data.text().then(function (r) {
eval(r);
})
});

}
// To not repeat the element
scripts[i].parentNode.removeChild(scripts[i]);
}
});

关于javascript - 我如何使用 fetch api 用它的 javascript 加载 html 页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57987543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com