首页 > 解决方案 > 如何在我的 html 中包含我的 header.html?

问题描述

我有一个 header.html 文件,我想将它包含在我的所有 HTML 文件中,我该怎么做?

我的 header.html 代码:

<html>
    <header id="header" class="header">
        <--code-->
    </header>
</html>

在我的 html 中,我尝试过:

<body>
    <!--#include file="layout/header.html" -->
</body>

并且还使用js:

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script>
        $(function () {
            $("#header").load("layout/header.html");
        });
    </script>
</head>
<body>
    <div id="header"></div>
</body>

我试过这个:在 HTML 文件中包含另一个 HTML 文件

但这对我不起作用,标题的内容不显示。可能是什么问题?我在 XAMPP 中尝试了 main.html,也尝试了它。我之前在 Firefox 中解释过的内容,但在 Chrome 中没有,为什么?当我发布网页时,header.html 不会在 Chrome 浏览器中加载?

Chrome 控制台错误:jquery.min.js:2 从源“null”访问 XMLHttpRequest 在“file:///C:/.../header.html”已被 CORS 策略阻止:仅支持跨源请求对于协议方案:http、data、chrome、chrome-extension、https。

标签: jqueryhtmlinclude

解决方案


您可以让您的服务器端代码手动解析标头和主 html 文件,并将它们拼接成一个有效的完整组合的 html 文档。这就像您自己的自定义模板引擎!


推荐阅读