我想拥有一个类型的许多HTML页面,唯一的区别是页面标题和一些数据存储在不同的.json文件中。其他一切应该存储在两个集中的文件中,一个.js和一个.html文件。在伪代码的网页应该是这样的:嵌入JS和HTML同时失败
<html>
<head>
include global_script.js
include specific_data_n.json
</head>
<body>
include global_body.html
</body>
</html>
在第n页包括数据文件specific_data_n.json但一切始终是相同的。
我知道如何在头文件中包含.js和.json文件。但是,我真的不知道如何在文本中包含.html文件。我在网上搜索,特别是,发现了这个问题:Server side includes alternative我尝试了包括在答案中提出的身体不同的方式,但无论我尝试,我得到一个JS错误。
这是一个问题的最小例子。首先,工作文件,其中身在主文件和不在一个额外的文件:
function init(){document.getElementById('demo').innerHTML = '2+2=4';}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><head>
<script language="javascript" type="text/javascript" src="minimal.js"></script>
</head>
<body onload="init();">
<div id="demo">
2+2=5
</div>
</body>
</html>
现在我试图把身体外部文件下面一个上面提到的问题的答案。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="javascript" type="text/javascript" src="minimal.js"></script>
</head>
<body onload="init();">
<!-- Content, inclusion from https://stackoverflow.com/questions/35249827/can-you-link-to-an-html-file -->
<div w3-include-html="body_minimal.html"></div>
<script>
(function() {
myHTMLInclude();
function myHTMLInclude() {
var z, i, a, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
if (z[i].getAttribute("w3-include-html")) {
a = z[i].cloneNode(false);
file = z[i].getAttribute("w3-include-html");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
a.removeAttribute("w3-include-html");
a.innerHTML = xhttp.responseText;
z[i].parentNode.replaceChild(a, z[i]);
myHTMLInclude();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
})();
</script>
</body>
</html>
并包含在body_minimal.html:
<div id="demo">
2+2=5
</div>
我也试过嵌入body_minimal.html文件不同的进一步方法(其中如果需要的话我可以提出),但他们没有工作,所以我认为这是一个根本性的问题。我总是得到错误的JS调试器:
TypeError: document.getElementById(...) is null
我要补充一点,我没有经验,无论是在HTML也不在CSS和我大多来自不同的教程,论坛和Q &一个网站,所以复制&粘贴的东西我真的不明白这个嵌入HTML文件的代码在做什么。 :)
感谢您提供什么问题可能会和新年快乐!
感谢您的建议!不幸的是,该网站托管在github.io上,它不提供PHP支持。 – Photon
@Photon - 试试你链接到的问题中评分较高的答案之一。 – Quentin
实际上,最高评分答案的作用最差,它只显示 {%include head.html%} {%include minimal_body.html%} 作为输出。其他的也导致我的问题中提到的JS错误... – Photon