gpt4 book ai didi

javascript - PHP 样式在 HTML 中插入文件内容

转载 作者:行者123 更新时间:2023-11-28 05:19:13 25 4
gpt4 key购买 nike

我有一个目录,它对我生成的许多 html 文件都是通用的。我希望所有这些都引用一个公用表,这样如果我更改该表,所有文件都会反射(reflect)它并且无需触摸它们。

是否有类似这样的 PHP 代码的客户端等效项?

<?php readfile("file.html"); ?>

我从未使用过 PHP,但我想避免安装服务器端程序以在本地查看 HTML 文件的需要。

谢谢。

最佳答案

您可以使用 JavaScript 动态加载 HTML 内容。

这是一个例子:

table_of_contents.html

<ul>
<li>Section I<li>
<li>Section II<li>
<li>Section III<li>
</ul>

您希望在其中包含目录的其他页面

<!DOCTYPE html>
<html>
<head>
<title>Some page</title>
</head>
<body>
<div id="table-of-contents"></div>

<p>Some content on your page</p>

<script>
document.addEventListener('DOMContentLoaded', function () {
// Create a XMLHttpRequest
var xhr = new XMLHttpRequest();
// When it loads, insert the HTML into the container
xhr.onload = function () {
document.getElementById('table-of-contents').innerHTML = this.response;
};

// Set the request parameters
xhr.open('GET', 'table_of_contents.html', true);
// Send the request
xhr.send();
}, false);
</script>
</body>
</html>

或者,如果您使用的是 jQuery,则可以用 .load() 做一行:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(function () {
$('#table-of-contents').load('table_of_contents.html');
});
</script>

Note that this method may only work on a server (using http://, not file:\\\), because of the Same Origin Policy that browsers implement for everyone's safety - you don't want some random website to load files from your system.

关于javascript - PHP 样式在 HTML 中插入文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41231801/

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