I am relatively new to jQuery and pardon if this question is too simple, but I've searched numerous threads for hours and cannot find a definite solution.
I have the following folder structure:
/index.html
/html/pages/page1.html
/html/pages/images/
/html/pages/css/
/html/pages/js/
/html/pages/includes/
I am trying to load page1.html into a DIV in index.html in the following basic way:
$('#content').load('html/pages/page1.html', function () {
console.log('loaded');
});
page1.html loads fine, however, it consists of multiple includes and all the content in it (images, CSS, JS, etc.) is relative to the pages folder (for example: ../images/header.jpg), so it does not show when loaded into index.html since now everything becomes relative to / or index.html.
I read somewhere that making all paths absolute or root relative in page1.html will work, also adding sort of a global path variable, however, the PROBLEM is that there is too much legacy content and changing all of it is not an option.
Is there a way to do load page1.html as described above without modifying any of the paths, despite that they're relative? Or can someone recommend an efficient way (other plugins, techniques) of loading external content this way?
Thank you!
If everything is relative to the pages
folder, then you can use some simple searching and replacing. This isn't the best programming practice, as it is not as flexible (going from relative to absolute in this type of context is relying on a number of factors working properly) as it should be, but it will work.
$.get('html/pages/page1.html', {}, function(data, status, xhr) {
var updatedData = data.replace(/\.\.\/(images|css|js)+/g, "http://www.mywebsite.com/html/$1");
$('#content').html(updatedData);
});
Edit:
You could also use a proxy script and rewrite/route all requests to this folder to the proxy script. I don't know what server-side technology you are using, but you could do this:
Using .htaccess
(or the like), redirect all requests directed to this folder to another script in your codebase. In the script, look for the path that is incoming to the script, load the original output contents, perform a search/replace and output the contents to the buffer. In addition, you can set up caching on the server so that the client would cache the requests lowering the processing overhead that you might experience (though, I would anticipate that to be fairly minimal).
来源:https://stackoverflow.com/questions/13812184/loading-external-html-page-with-relative-paths-into-a-div-using-jquery