Javascript 如何在Javascript中获取相对路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6310620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get relative path in Javascript?
提问by Vivian River
In my ASP.net web project, I've written the following Javascript code in a .js file:
在我的 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;
}
It was working great until I tried to load this .js file into a page in a subdirectory.
在我尝试将此 .js 文件加载到子目录中的页面之前,它运行良好。
Let's suppose that the name of my project is widget
.
假设我的项目名称是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.
当我在主虚拟目录中使用此代码时,Javascript 解释Controls/ModelSelectorWebMethods.aspx/getDeviceTypes
为意思https://mysite.com/widget/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes
并且一切正常。但是,从子目录中的页面,Javascript 将其解释为意思https://mysite.com/widget/subdirectory/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes
并且它不起作用。
How can I write my Javascript code so that the AJAX web method can be called from pages in any directory in my application?
如何编写 Javascript 代码,以便可以从应用程序中任何目录中的页面调用 AJAX Web 方法?
回答by Matt
You've got two options:
你有两个选择:
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 forconfig.base
whether 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 allrelative URL's: image's, links etc.
在 JavaScript 中构建一个配置/首选项对象,其中包含您的所有环境特定设置:
var config = { base: <% /* however the hell you output stuff in ASPX */ %>, someOtherPref: 4 };
然后在 AJAX url 前面加上前缀
config.base
(并更改config.base
您是否在开发/测试/部署服务器上的值。)使用
<base />
HTML 标记为所有相对 URL 设置 URL 前缀。这会影响所有相对 URL:图像、链接等。
Personally, I'd go for option 1. You'll most likely find that config object coming in handy elsewhere.
就我个人而言,我会选择选项 1。您很可能会发现该 config 对象在其他地方派上用场。
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.
显然,配置对象必须包含在评估服务器端代码的站点中;一个.js
没有自己的服务器配置文件将不会削减它。我总是在 HTML 中包含 config 对象<head>
;它是一个小的配置对象,其内容可以在每个页面上更改,因此最好将其粘贴在那里。
回答by Jamie Treworgy
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:
只要你不关心 asp.net虚拟目录(这使得实际上无法从脚本中找出来,你必须从服务器传递一些东西)你可以查看 URL 并解析它:
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#:
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) Change baseUrl to include that:
2) 更改 baseUrl 以包括:
function baseUrl() {
var href = window.location.href.split('/');
return href[0]+'//'+href[2]+basePath;
}
回答by Josh Stodola
Create an app root variable...
创建应用根变量...
var root = location.protocol + "//" + location.host;
And use an absolute URI (instead of relative) when you are making AJAX requests...
并在发出 AJAX 请求时使用绝对 URI(而不是相对)...
url: root + "/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes"
回答by Paulo Salazar
I think this function will work... it is to get a relative path as "../../../" so if you invoke this function in each page, this will return a relative path format.
我认为这个函数会起作用......它是获取一个作为“../../../”的相对路径,所以如果你在每个页面中调用这个函数,这将返回一个相对路径格式。
function getPath() {
var path = "";
nodes = window.location. pathname. split('/');
for (var index = 0; index < nodes.length - 3; index++) {
path += "../";
}
return path;
}
回答by user3869206
You can import the namespace at the beginning: System.Web.Hosting.HostingEnvironment
可以在开头导入命名空间:System.Web.Hosting.HostingEnvironment
<%@ Master Language="VB" AutoEventWireup="false" CodeFile="Site.master.vb" Inherits="Site" %> <%@ Import namespace="System.Web.Hosting.HostingEnvironment" %>
<%@ Master Language="VB" AutoEventWireup="false" CodeFile="Site.master.vb" Inherits="Site" %> <%@ Import namespace="System.Web.Hosting.HostingEnvironment" %>
and on js:
在 js 上:
<script type="text/javascript"> var virtualpathh = "<%=ApplicationVirtualPath %>"; </script>
<script type="text/javascript"> var virtualpathh = "<%=ApplicationVirtualPath %>"; </script>
回答by David Fox
Could you use window.location.pathname
?
你能用window.location.pathname
吗?
var pathname = window.location.pathname;
$.ajax({
//...
url: pathname + 'Controls/...', // might need a leading '/'
//...
});