Search code examples
javascriptjqueryxmlhttprequest

XHR loading resources from separate directory


I have a simple XHR to load 'testdirectory/testpage.html'

var xhr; (XMLHttpRequest) ? xhr= new XMLHttpRequest() : xhr= new ActiveXObject("Microsoft.XMLHTTP"); 

xhr.onload = function() {
    if(xhr.readyState === 4 && xhr.status === 200) {
        var preview = xhr.responseText;
        document.getElementById("content").innerHTML = preview;

    }
}           
xhr.open("GET", "testdirectory/testpage.html", true);
xhr.send();

I have it set up to display on button click. Works great. Let's say testpage.html looks like this:

<h1>Loaded Page Heading!</h1>
<img src="main.png">

It will load but the image that is displaying is not main.png from that directory, it is main.png from the directory of the page that placed the XHR.

Is there a way to get the returned HTML to point to the 'testdirectory/main.png' image and not just use the current directory from the XHR? I'm looking for an alternative to changing the HTML of the page retrieved since that would defeat the purpose of what I'm trying to do.

I've been searching through StackOverflow for about 20 minutes, and I've googled a couple of different things. It seems like a question that must have been asked sometime before but is difficult to phrase/find.


Solution

  • I'm afraid you won't be able to achieve what you want without changing the retrieved HTML.

    The xhr.responseText you receive from the XHR request is a string of HTML. When you do:

    document.getElementById("content").innerHTML = preview;
    

    you're taking that string of HTML and assigning it to the innerHTML property of that element. The innerHTML property parses that string of HTML and assigns the resulting nodes as children of the element. Any URLs in that parsed HTML will use the current document's base URL.

    So basically, all you did was take some HTML string, parse it and append it to the current document. The innerHTML property doesn't care or know from where you obtained that HTML. The resulting nodes will behave exactly as any other HTML in the rest of the document.

    It seems to me you're expecting the behavior of an iframe. But that's a totally different beast, and works differently to what you're doing here. An iframe is basically an embedded document, with it's own DocumentObjectModel (DOM) and, therefore, it's own base URL property.


    In case you decide it's acceptable to modify the HTML string, you could do something like this:

    var preview = xhr.responseText.replace('src="', 'src="testdirectory/');
    

    Have in mind though that you would need to do the same for URLs in other types of attributes, such as href.