In my ASP.net web project, I’ve written the following Javascript code in a .js file:
function getDeviceTypes() {
var deviceTypes;
$.ajax({
async: false,
type: "POST",
url: "Controls/ModelSelectorWebMethods.aspx/getDeviceTypes",
data: '{ }',
contentType: "application/json;",
dataType: "json",
success: function(response) {
deviceTypes = response.d;
},
error: function(xhr, status) {
debugger;
alert('Error getting device types.');
}
}); // end - $.ajax
return deviceTypes;
}
It was working great until I tried to load this .js file into a page in a subdirectory.
Let’s suppose that the name of my project is widget.
When I use this code in the main virtual directory, Javascript interprets Controls/ModelSelectorWebMethods.aspx/getDeviceTypes to mean https://mysite.com/widget/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes and all is well. However, from the page in a subdirectory, Javascript interprets it to mean https://mysite.com/widget/subdirectory/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes and it doesn’t work.
How can I write my Javascript code so that the AJAX web method can be called from pages in any directory in my application?
You’ve got two options:
Build a configuration/ preferences object in JavaScript which contains all your environment specific settings:
and then prefix the AJAX url with
config.base(and change the value forconfig.basewhether you’re on a dev/ testing/ deployment server.)Use the
<base />HTML tag to set the URL prefix for all relative URL’s. This affects all relative URL’s: image’s, links etc.Personally, I’d go for option 1. You’ll most likely find that config object coming in handy elsewhere.
Obviously the config object will have to be included in a part of your site where server-side-code is evaluated; a
.jsfile won’t cut it without configuring your server. I always include the config object in the HTML<head>; its a small config object, whose contents can change on each page, so it’s perfectly warrented to stick it in there.