使用加载的文档路径作为其相对路径的根来加载HTML,而不是使用源文档的路径。

3

我有一个类似这样的东西,

<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秒后显示它),因此仅在3秒后执行window.location='../stats.phtml'不是一个好的解决方案。我也希望保留已加载文档中的相对链接,而不是将它们转换为绝对链接。有什么建议吗?

1个回答

2

我发现在阅读mozilla开发者网站上的这篇文章时,得知在进行替换之前可以使用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!
    }

享受吧!


我目前正在尝试你在更新中提到的内容,但在Firefox中遇到了各种问题。似乎pushstate和document.open不太兼容。你在Firefox中是如何实现的? - gmustudent
已经过去一年多了,但我完全没有遇到任何问题。请查看https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history#The_pushState().C2.A0method(抱歉回复晚了)。 - NotGaeL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接