基本上,我正在尝试构建一个功能,在其中我只真正编辑我的index.php,我有很多其他 php 文件,其中只有一个表单或只有几行文本。
我想要实现的是将这些其他文件加载到contentwrapper
中我的index.php。
我已经成功地用 iframe
做到了这一点并带有 html <object>
.
但这些的问题是,首先它们加载一个全新的 #document
在 DOM 中,而且我的网页没有设置高度,所以 height: 100%
对这些不起作用,我会得到这些丑陋的滚动条之类的东西。
今天在 SO 上进行了大量搜索后,我发现了一些有趣的解决方案,并将其组合起来,这就是我现在正在尝试的:
<script type="text/javascript" href="js/csi.min.js"></script>
<script type="text/javascript">
function load_content(target){
document.getElementById('contentwrapper').innerHTML='<div data-include="' + target + '" ></div>';
return false;
}
</script>
现在你可能会问什么data-include
是的,这是我在 SO 上发现的一个非常好的解决方法。
THIS is what it does ,它基本上调用一个 .js 文件,该文件用文件 (target in the above example)
中的数据替换包含元素。
我这样称呼这个功能:
<a href="#" onclick="load_content('update.php');">Update profile</a>
只要将其添加到 DOM 即可:
<div id="contentwrapper">
<div data-include="update.php" ></div>
</div>
但除此之外它什么也不做,我认为它不会调用 data-include 属性的 .js 文件。但我找不到解决这个问题的办法。
(顺便说一句:如果我在没有 JavaScript 的情况下手动将 data-include 属性放入标签中,则 data-include 属性确实有效)
我希望我没有过度解释情况,我感谢所有提前提供帮助的人!
最佳答案
csi.js脚本仅在页面加载后运行一次。它只是使用 data-include
属性遍历所有元素并运行 fragment
函数。
<script type="text/javascript">
function fragment(el, url) {
var localTest = /^(?:file):/,
xmlhttp = new XMLHttpRequest(),
status = 0;
xmlhttp.onreadystatechange = function() {
/* if we are on a local protocol, and we have response text, we'll assume
* things were sucessful */
if (xmlhttp.readyState == 4) {
status = xmlhttp.status;
}
if (localTest.test(location.href) && xmlhttp.responseText) {
status = 200;
}
if (xmlhttp.readyState == 4 && status == 200) {
el.outerHTML = xmlhttp.responseText;
}
}
try {
xmlhttp.open("GET", url, true);
xmlhttp.send();
} catch(err) {
/* todo catch error */
}
}
function load_content(target){
fragment(document.getElementById('contentwrapper'), target);
return false;
}
</script>
然后这样调用它:
<a href="#" onclick="load_content('update.php');">Update profile</a>
因此,您唯一需要的就是为新创建的元素调用此函数。将 DOM 元素和 url 传递给此函数,它将负责将所请求资源的内容加载到相应的元素中。
关于javascript - javascript 函数从其他文件加载内容的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27150903/