How to get relative path in Javascript?

前端 未结 6 685
野的像风
野的像风 2020-12-09 18:47

In my ASP.net web project, I\'ve written the following Javascript code in a .js file:

function getDeviceTypes() {
    var deviceTypes;
    $.ajax({
        a         


        
6条回答
  •  粉色の甜心
    2020-12-09 19:24

    As long as you don't care about asp.net virtual directories (which makes it actually impossible to figure out from script, you'll have to pass something from the server) you can look at the URL and parse it:

    function baseUrl() {
       var href = window.location.href.split('/');
       return href[0]+'//'+href[2]+'/';
    }
    

    then:

    ...
       url: baseUrl()+"Controls/ModelSelectorWebMethods.aspx/getDeviceTypes",
    ...
    

    ... and now I see from your comments above that virtual directories are a problem. I usually do this.

    1) In your masterpage, put code to inject a script somewhere, preferably before anything else (I add it directly to HEAD by adding controls instead of using ScriptManager) to make sure it's run before any other script. c#:

    string basePath = Request.ApplicationPath;
    // Annoyingly, Request.ApplicationPath is inconsistent about trailing slash
    // (if not root path, then there is no trailing slash) so add one to ensure 
    // consistency if needed
    string myLocation = "basePath='" + basePath + basePath=="/"?"":"/" + "';";
    // now emit myLocation as script however you want, ideally in head
    

    2) Change baseUrl to include that:

    function baseUrl() {
       var href = window.location.href.split('/');
       return href[0]+'//'+href[2]+basePath;
    }
    

提交回复
热议问题