NotGaeL
NotGaeL

Reputation: 8484

Load HTML using loaded document's path as root for its relative paths instead of source document's path

Well I have something like this,

<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>

And it doesn't found any external documents linked in the loaded document stats.phtml (javascript and css sources), because the path for the relative paths is the path where the document is, instead of the loaded document's root path.

I need to do this on AJAX (the loading page is supposed to be executing a script while the content is being loaded and show it after 3 seconds have passed), so just doing window.location='../stats.phtml' after the 3 seconds is not a good solution. I'd also like to keep the relative links in the loaded doc instead of moving them to absolute ones. Any suggestions?

Upvotes: 3

Views: 975

Answers (1)

NotGaeL
NotGaeL

Reputation: 8484

I found out reading this article on mozilla developer that html5 window.history.pushState can be used before making the substitution, like this:

if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
    var stateObj = { foo: "stats" };
    window.history.pushState(stateObj, "Title", "../stats.phtml");
    $("body").html(xmlhttp.responseText);
}

Wich is fair enough for me.

Otherwise, I read # marks can be used to identify the documents and switch one URL for the other without reloading (in combination with some Apache modrewrite spells to change the # notation to actual directories in the server, I guess). If you know exactly how, any example using this approach would be appreciated.

update I've been working on this for some time and I found a non-jquery alternative which replaces the whole document content and suits me better in this case.

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!
    }

Enjoy!

Upvotes: 2

Related Questions