Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

jquery - How to get relative path in Javascript?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...