如何在Javascript中获取相对路径?

在我的ASP.net Web项目中,我在.js文件中编写了以下Javascript代码:

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; } 

在我尝试将此.js文件加载到子目录中的页面之前,它工作得很好。

我们假设我的项目名称是widget

当我在主虚拟目录中使用此代码时,Javascript将Controls/ModelSelectorWebMethods.aspx/getDeviceTypes解释为https://mysite.com/widget/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes ,一切都很好。 但是,从子目录中的页面,Javascript将其解释为https://mysite.com/widget/subdirectory/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes ,它不起作用。

如何编写我的Javascript代码,以便可以从我的应用程序中任何目录中的页面调用AJAX Web方法?

你有两个选择:

  1. 在JavaScript中构建配置/首选项对象,其中包含所有特定于环境的设置:

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

    然后使用config.base为AJAX url添加前缀(并更改config.base的值,无论您是在dev /测试/部署服务器上。)

  2. 使用 HTML标记为所有相对URL设置URL前缀。 这会影响所有相对URL:图像,链接等。

就个人而言,我会选择选项1.您很可能会发现配置对象在其他地方派上用场。

显然,配置对象必须包含在评估服务器端代码的站点的一部分中; 如果不配置服务器, .js文件将不会删除它。 我总是在HTML 包含配置对象; 它是一个小的配置对象,其内容可以在每个页面上更改,因此将其粘贴在那里是完全可靠的。

只要你不关心asp.net 虚拟目录 (这使得它实际上无法从脚本中找出,你必须从服务器传递一些内容),你可以查看URL并解析它:

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

然后:

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

…现在我从上面的评论中看到虚拟目录是个问题。 我通常这样做。

1)在你的母版页中,放置代码以在某处注入脚本,最好是在其他任何东西之前(我通过添加控件而不是使用ScriptManager将它直接添加到HEAD)以确保它在任何其他脚本之前运行。 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)更改baseUrl以包含:

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

创建应用程序根变量…

 var root = location.protocol + "//" + location.host; 

在进行AJAX请求时使用绝对URI(而不是相对)…

 url: root + "/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes" 

我认为这个函数可以工作……它是一个相对路径为“../../../”所以如果你在每个页面中调用这个函数,这将返回一个相对路径格式。

 function getPath() { var path = ""; nodes = window.location. pathname. split('/'); for (var index = 0; index < nodes.length - 3; index++) { path += "../"; } return path; } 

您可以在开头导入名称空间:System.Web.Hosting.HostingEnvironment

  <%@ Master Language="VB" AutoEventWireup="false" CodeFile="Site.master.vb" Inherits="Site" %> <%@ Import namespace="System.Web.Hosting.HostingEnvironment" %> 

并在js上:

   

你能用window.location.pathname吗?

 var pathname = window.location.pathname; $.ajax({ //... url: pathname + 'Controls/...', // might need a leading '/' //... });