When doing AJAX request in JavaScript, is there any case where it could be necessary to write
window.location.protocol + '//' + window.location.host
instead of simply
/
After all, files like images, scripts, and css are always specified relative so it should be the same when making ajax requests.
The reason I'm asking this is because I can't find any official suggestion (e.g. from w3c) on how to do it.
They're not strictly the same, as window.location.protocol + '//' + window.location.host is missing the trailing slash to indicate the root directory. But for all intents and purposes, they can be used interchangeably.
In practical usage, assuming you're not using <base>, all of the following will point to the same place:
window.location.protocol + '//' + window.location.host + '/'
window.location.href
'//' + window.location.host + '/' //useful if you don't know the scheme and don't want to check
'/'
window.location.host contains the port number if it's anything other than 80, so you shouldn't have to worry about including that. It's simpler and clearer to write '/', as it always means "the root directory of whichever server this page came from." Things could get hairy if the URI contains something like username:password@ -- I don't know of a way to get that data using JS. Trying to reassemble a URI from individual components could cause problems if the code is migrated to an unusual environment like that.
The formal definition for all of this is in RFC3986, which is not exactly light reading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With