我是网络开发新手,所以我觉得我错过了一些简单的东西。我真的只是需要有人指出我错过了什么?
我正在尝试使用 jquery load() 函数将本地 html 文件包含到另一个 html 文件中。我遵循了其他人的一些建议stackoverflow posts 。看起来它应该非常简单并且工作正常,但它不起作用。我确实将 jquery 源添加到了 head 中,并确保我在正文中插入的部分包含正确的 div id。我不需要插入本地 html 的特定部分,只需插入整个内容。该 html 只是文本,仅包含 <p>
标签和类似的东西。
代码如下:
<html>
<head>
<meta charset="utf-8" />
<title>letters on the road</title>
<link rel="stylesheet" type="text/css"
href="../assets/css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function(){
$("#includedContent").load("text-012518.html");
});
</script>
</head>
<body style="font-family:Andale Mono Regular">
<div id="includedContent"></div>
<a href="../index_v2.html">home</a>
</body>
</html>
我觉得 jquery load 似乎是最干净的选择。我确实尝试使用对象标签,但它将文本放在窗口一 Angular 的一个可滚动的小框中。我对 css 不太熟悉来修复它,所以仍然希望 jquery load 能够正常工作。
我上面的代码不会抛出错误,它只是根本不包含外部 html 中的任何内容。 (外部 html 中的文本确实显示了对象,所以我认为这不是外部 html 本身的问题。)我也尝试过没有 $(function(){});
的代码。包装器,它也不起作用。
最佳答案
大多数堆栈溢出解决方案( Answer 1 、 Answer 2 等等)都不起作用。使用 Jquery .load()
实现的解决方案或XMLHttpRequest
由于 CORS 问题而失败(至少在 chrome 上)。解决方法是通过添加 --disable-web-security
来禁用安全性。标志或使用 CORS chrome extension
,两者都只适合测试,不适用于生产应用程序。
Access to XMLHttpRequest at 'file:///.../text.html' from origin 'null' has been blocked by CORS policy:
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
这两种方法有效 -
- 使用
<object>
标签 -
<object data="test.html"></object>
- 使用
iframe
标签 -
<iframe src = "test.html" height="80px" width="500px" >
我的方法是使用 Jquery/vanila javascript 来加载 html,使用 object
标签。添加script
标签到页面底部。寻找更多答案。
<script>
document.getElementById("includedContent").innerHTML='<object data="text.html"></object>';
</script>
关于javascript - 在 html 中包含 html,jquery load 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61977782/