Liliput Liliput - 1 year ago 50
jQuery Question

How to handle host name during Ajax call?

I am making an ajax call:

var hostUrl = location.hostname;
$.getJSON(hostUrl + "/DataMatrix/ItemTypeList/" + $("#filter > option:selected").attr("value"),
function (dataValue) {

This is what I get in my network tab:


Localhost gets appended on top of local host, however in production it works fine as url formed is (xyz: host placeholder).


Once I remove host url then it works great in local too, but fail in production:

$.getJSON("/DataMatrix/ItemTypeList/" + $("#filter > option:selected").attr("value"),
function (dataValue) {

How to handle such scenario during development so that I don't have to change the string when I am handing over the files to deployment team.


just remove the leading "/" ie:

$.getJSON("DataMatrix/ItemTypeList/" ...

This is because the the browser will automatically interpret the URL as being relative to the current host (e.g. "http://localhost:50020/" or "") and prepend that to your stated URL.

So if you put "DataMatrix/ItemTypeList" in your URL when deployed on "", the ajax call will automatically make the call to "".