Relative URLs in AJAX requests

Why does Javascript treat relative URLs differently than standard HTML? Think of the following URL (or just browse to it): Open a Firebug console (or another Javascript console) and enter the following:

var x = new XMLHttpRequest();"GET", "foo", true);

Under my system the request is sent to "". The "Rome" in the URL is simply ignored. The same request with a trailing slash in the URL ("") appends the "foo" to the full URL.

This seems to make it pretty hard to encode the correct URLs in Javascript. Are there any Javascript libraries that help to overcome this problem?

(I asked a similiar question before, but more jQuery specific, where this also happens. I hope I get a better answer with this somewhat more library independent question.)



(updated to make it more readable)

This is how relative paths is supposed to work.

Pretend that the current address is this:

Absolute: protocol://

If you specify only a new filename "foo", you get the same protocol, host and dirs, only the file name is changed:

Relative: foo

Absolute: protocol://

If you specify a whole path "/dir3/filename2" you get the same protocol and hostname but with another path:

Relative: /dir3/filename2

Absolute: protocol://

You can also specify host name "//" and get the same protocol but another host, dir and filename:

Relative: //

Absolute: protocol://

What might be confusing is that a webserver internally can add a / at the end of the url if the specified url points to a directory and not to a file.


If "somename" is a directory the webserver might translate it to (possible with a redirect)



As cameron said in a comment: For reference, see step 6 in section 4 of RFC 1808


Looks like is the library of choice for URL manipulation in general and this type of absolute-to-relative computation in particular:

new URI(potentiallyRelativeLink).resolve(new URI(window.location.href)).toString()


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.