views:

49

answers:

1

I'm trying to figure out how to resolve relatively referenced resources inside dynamically loaded content. For example, suppose I had the following page downloaded from /index.html:

<html><body>
 <div id="insert-here" />
 <script>
  $(function(){
   $("#insert-here").load("x/ajax-content.html");
  });
 </script>
</body></html>

And ajax-content.html contains:

<img href="foo.png"/>

Then foo.png will be downloaded from /foo.png, which is not what I want. I need the foo.png to be downloaded relative to the HTML that referenced it, so I need it downloaded from /x/foo.png. I'm wondering if there is a way to do this (aside from using an absolute path in ajax-content.html)?

(Why would I want to do this? I am developing an AJAX-based plug-in architecture that allows blocks of page content to be developed and deployed independent of the application.)

+3  A: 

The problem is that you are inserting the arbitrary HTML into the originating document. The browser has no way of knowing that the data in question is actually from another document. Here is a breakdown of what is going on:

DOM (before):

<html><body>
  <div id="insert-here"></div>
</body></html>

DOM (after):

<html><body>
  <div id="insert-here"><img src="foo.png"></div>
</body></html>

The fact that the html snippet in question came from some other html reference is lost because of the way the data was inserted. I would say that the easiest solution is to change the paths that are in the ajax-content.html file. You could do this either in the file itself (perhaps automatically through whatever tool uploads the ajax plugins) or else mangle the paths after the document is loaded. So instead of doing

$("#insert-here").load("x/ajax-content.html");

You'd have to get the data, then adjust any paths, then insert the data into the DOM.

function updatePaths(responseText, textStatus, XMLHttpRequest) {
  // check xmlHttpRequest status code
  // parse responseText, fix up relative URLs
}
$("#insert-here").load("x/ajax-content.html", null, updatePaths);
Mr. Shiny and New