Mia
Mia

Reputation: 6531

Loading html with ajax, and relative paths

I use ajax to load html files when the links on my page are clicked. Here is the simplified version of what's going on:

links.click(function () {
    var href = $(this).attr("href");
    history.pushState(null, null, href);
    $.get($(this).attr("href"), function(data){
        $("#page").html(data)
    })
});

This works fine. However, the loaded .html files contain a lot of images with relative paths, as follows:

<img src="smiley.gif">

Therefore, when the files are loaded, the text of the page is okay but none of the relative content is being loaded properly. Creating my images with absolute paths solve my problem however I need them to be relative for my current case.

As you've noticed I've modified the address bar by using history.pushstate in my click event function. I assumed that the loaded url would load all of the resources properly as the url is also modified. However, it's not working like that with the code above.

What can I do to fix this issue in an elegant and simple way?

Upvotes: 1

Views: 689

Answers (2)

trevorgrayson
trevorgrayson

Reputation: 1867

It's not clear to see what the URL you are on, which is ultimately going to affect how your page reacts.

For instance if you are on a page that looks like www.example.com/products and you try to load smiley.gif that's going to end up being www.example.com/smiley.gif.

If instead you are on www.example.com/products/ (NOTE: trailing slash) or www.example.com/products/index.html however, smiley.gif would point to www.example.com/products/smiley.gif. You don't know what URL the user is going to type in, but you could:

  1. update your links to include the final slash to mitigate this, and
  2. forward the user to a location with the trailing slash if they type it in incorrectly.

One slash on the end of your URL may be all that you need to fix this but... you may want to consider putting all your asset files into one directory so you don't have to play this game at all! /images/smiley.gif could end up being easier for you in this case.

Upvotes: 1

Stefan
Stefan

Reputation: 4130

What you want is to insert a base tag in your resulting html, to specify where to root of all relative paths should be at.

So lets say that all your relative paths should be served from /assets and you load /user/1/profile, a relative image with: <img src="nyan.gif" /> would be checked at /user/1/profile/nyan.gif and will be returned invalid. If you however insert a <base href="/assets"> in the head tag, the image will be served correctly

Upvotes: 1

Related Questions