Relative URLs in AJAX requests

后端 未结 2 1903
感情败类
感情败类 2020-11-27 14:29

Why does Javascript treat relative URLs differently than standard HTML? Think of the following URL (or just browse to it): http://en.wikipedia.org/wiki/Rome. Open a Firebug

相关标签:
2条回答
  • 2020-11-27 14:52

    Looks like http://code.google.com/p/js-uri/ 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()
    
    0 讨论(0)
  • 2020-11-27 15:00

    (updated to make it more readable)

    This is how relative paths is supposed to work.

    Pretend that the current address is this:

    Absolute: protocol://some.domain.name/dir1/dir2/filename


    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://some.domain.name/dir1/dir2/foo


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

    Relative: /dir3/filename2

    Absolute: protocol://some.domain.name/dir3/filename2


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

    Relative: //another.domain.name/dir5/filename3

    Absolute: protocol://another.domain.name/dir5/filename3


    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.

    protocol://some.domain.name/somename

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

    protocol://some.domain.name/somename/


    UPDATE

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

    0 讨论(0)
提交回复
热议问题