如何将 HTML 代码从另一个文件添加到 .html 文件?
我想输入一些代码,例如来自另一个文件的 HTML 菜单,以便我可以编辑该菜单,然后所有站点的所有菜单都会在链接到该页面时发生变化。有没有办法在不将所有页面都设为 .php 的情况下做到这一点?
I'd like to input some code, for example a menu in HTML from another file so that I can edit that menu and then all the menus for all the sites would change as they'd be linked to that page. Is there a way to do so without making all the pages .php?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
服务器端包含将是执行此操作的最佳方法,但如果这确实不是一个选项,您可以使用 JavaScript 来完成 - 在加载第一个页面时使用 AJAX 加载另一个文件的内容,并将该内容插入到指定元素中在第一页上。
例如(使用 jQuery,因为在这里写起来更简单):
$.get('page2.html', function(data) { $('#whereToPutContent').html(data); });< /代码>
Server side includes are going to be the best way to do this, but if that's really not an option you could do it with JavaScript - load the contents of another file using AJAX when the first page loads, and insert that content into a specified element on the first page.
For example (using jQuery, because it's simpler to write out here):
$.get('page2.html', function(data) { $('#whereToPutContent').html(data); });
您不需要将所有页面都放在 php 中。只要您要包含的页面没有 php 代码,它就可以是纯 html、txt 或其他任何内容。
include 必须位于 php 页面中,仅此而已。
因此,在您的 PHP 页面中,只需使用 include(或 require)即可。例如:
You don't need to make all the pages in php. As long as the page you're going to include doesn't have php code, it can be pure html, or txt, or whatever.
The include HAS to be in a php page, that's all.
So, in your PHP page, just use include (or require) and you're set. For example:
是的,可以使用框架或 AJAX(使用
<脚本源>
)。但是,框架已被弃用,并且 AJAX 仅在浏览器启用了 JavaScript 的情况下才可靠。所以 PHP 是这里(唯一的)解决方案。以下是四种可能性:
您可能想要使用
include_once
用于菜单,以便仅包含一次。或者,如果您确定仅包含一次,则可以使用include
。require
如果找不到文件则停止脚本,所以这可能不是您想要的。Yes, it's possible with frames or AJAX (use
<script src>
). However, frames are deprecated and AJAX is only reliable if the browser has JavaScript enabled.So PHP is the (only) solution here. Here are the four possibilities:
You probably want to use
include_once
for a menu so that it is only include one time. Or if you are sure that it is only included one time you can just useinclude
.require
stops the script if it can't find the file, so that's probably not what you want.您可以使用服务器端包含(SSI):
或
或
iframe:
或 javascript (AJAX):
第 1 步:将代码添加到 html 文件
步骤 2:通过添加以下内容来配置 [apache] 服务器.htaccess 文件。添加这一行:
You may use server-side includes (SSI):
or
or
iframes:
or javascript (AJAX):
STEP 1: add code to html file
STEP 2: configure [apache] server by adding to .htaccess file. Add this line:
包括菜单页面在内的页面必须是 PHP 的,是的,菜单页面本身不必是 PHP。为此,您可以使用: include()
The pages including the menu page would have to be PHP yes, the menu page itself doesn't have to be. For this you can use: include()
您可以使用 JavaScript 动态显示菜单(或其他内容)。
you can dynamically display menus (or whatever) with JavaScript.