好吧,我有这样的东西,
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
Loading your content...
</body>
<script type="text/javascript">
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
$("body").html(xmlhttp.responseText);
}
};
xmlhttp.open("GET","../stats.phtml",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
</script>
</html>
并且它没有在加载的文档stats.phtml(javascript和css源)中找到链接的任何外部文档,因为相对路径的路径是文档所在的路径,而不是加载文档的根路径。
我需要在 AJAX 上执行此操作(加载页面应该在加载内容时执行脚本并在 3 秒后显示),所以只需执行 window.location='../stats。 3 秒后的 phtml' 不是一个好的解决方案。我还想在加载的文档中保留相对链接,而不是将它们移动到绝对链接。有什么建议吗?
最佳答案
我发现阅读 this article on mozilla developer可以在进行替换之前使用 html5 window.history.pushState,如下所示:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var stateObj = { foo: "stats" };
window.history.pushState(stateObj, "Title", "../stats.phtml");
$("body").html(xmlhttp.responseText);
}
这对我来说足够公平了。
否则,我读到 # 标记可用于识别文档并在不重新加载的情况下将一个 URL 切换为另一个 URL(我猜想结合一些 Apache modrewrite 拼写将 # 符号更改为服务器中的实际目录)。如果您确切知道如何使用此方法,我们将不胜感激。
更新 我已经为此工作了一段时间,我发现了一个非 jquery 的替代方案,它取代了整个文档内容,在这种情况下更适合我。
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var stateObj = { foo: "stats" };
window.history.pushState(stateObj, "Title", "../stats.phtml");
document.open('text/html');
document.write(xmlhttp.responseText);
document.close(); // don't forget to do this, or you'll be in trouble!
}
尽情享受吧!
关于javascript - 使用加载文档的路径作为其相对路径的根而不是源文档的路径来加载 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8573811/