Accessibility Navigation

Quick Code: Get the domain name in JS

Posted on 10th June 2009 by Jacob

When your developing a site or online application that uses a lot of XML HTTP Requests (XHR) it’s generally a good idea to use a full URL when creating a request. If you then try to re-use your code across multiple sites and domains, you will find you get errors due to posting to a different domain than the current site.

Solving this problem is easy and will make your Javascript (JS) code more re-usable and easier to manage. All you need to do is create a global variable at the start of your JS file to automagically get the sites domain so you can append it to all your XHR calls.


var DOMAIN = 'http://'+document.domain+'/';

Then just use this variable with all your XHR calls.

Easy!


Have Your Say

Have Your Say Form









Comments

  • Be the first to add your voice to this post!

    Start the discussion and leave your views or thoughts by writing a comment using the form above.