Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  44] [ 5]  / answers: 1 / hits: 53817  / 13 Years ago, fri, june 10, 2011, 12:00:00

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?


More From » jquery

 Answers
15

You've got two options:




  1. Build a configuration/ preferences object in JavaScript which contains all your environment specific settings:



     var config = {
    base: <% /* however the hell you output stuff in ASPX */ %>,
    someOtherPref: 4
    };


    and then prefix the AJAX url with config.base (and change the value for config.base whether you're on a dev/ testing/ deployment server.)


  2. 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 .js file 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.


[#91764] Thursday, June 9, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
theron

Total Points: 168
Total Questions: 93
Total Answers: 94

Location: South Georgia
Member since Fri, Nov 13, 2020
4 Years ago
;