![](/img/trans.png)
[英]How to reuse angular-js common mark up (e.g. widget) without requesting external page?
[英]How to load an external HTML page within a specific JavaScript code? E.g. Within a JS function
我是这个网站的新手,不确定它的工作原理以及是否有人会回答我的问题,但是值得一试,因此请在此处发布我的问题! :)
基本上,我有一个HTML页面,其中包含页面不同部分的内容,这是我的代码:
<html>
<head>
<title>Welcome to My 1st JavaScript Page</title>
</head>
<body>
<script type="text/javascript">
//
var parameter = document.location.search.replace("?", "").replace("=", "");
// IF NO PARAMETER
if (!document.location.search || !parameter) {
document.write("No parameter is defined. Please either set ?pictures, ?videos or ?music");
// IF PARAMETER
} else {
// IF GAMES
if (parameter == "pictures") {
// FOR EXAMPLE INCLUDE THE PICTURES.HTML
// IF VIDEOS
} else if (parameter == "videos") {
// FOR EXAMPLE INCLUDE THE VIDEOS.HTML
// IF MUSIC
} else if (parameter == "music") {
// FOR EXAMPLE INCLUDE THE MUSIC.HTML
}
}
</script>
</body>
</html>
此页面将根据我设置的URL参数加载不同的内容,因此,当调用不同的URL参数时,我想在同一页面中加载不同的外部HTML页面,并且不想使用iframe等! 这有可能吗? 请在上面查看我的代码!
在PHP中,我们使用:
<?php
include ("./includes/music.html");
?>
但是我不知道如何用JavaScript做到这一点! 有人可以帮我这个忙!
谢谢 :)
您将需要Ajax,如下所示:
function include(page) {
var rq = null;
if(window.XMLHttpRequest) {
rq = new XMLHttpRequest();
} else if(window.ActiveXObject) {
try { rq = new ActiveXObject("Msxml2.XMLHTTP"); } catch(o) { try { rq = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} }
}
if(rq) {
try {
rq.open("GET", page, false);
rq.send(null);
document.body.innerHTML = rq.responseText;
} catch(ex) {
// Provide a fallback here, probably a redirect
}
} else {
// Provide a fallback here, probably a redirect
}
}
尝试使用模板引擎将数据加载模板。
有许多模板引擎,例如EJS , mustache , jQuery-tmpl 。
一般的想法是根据您的URL向服务器请求一些模板文件,并使用模板引擎来呈现它。 您还可以请求JSON数据来填充模板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.