有没有一种聪明的方式在JavaScript中进行基于“根”路径引用,就像ASP.NET中的~/
一样?
有没有一种聪明的方式在JavaScript中进行基于“根”路径引用,就像ASP.NET中的~/
一样?
让你的页面生成一个类似以下内容的标签:
<link rel="home" id="ApplicationRoot" href="http://www.example.com/appRoot/" />
然后,在JavaScript中编写一个提取值的函数,例如:
function getHome(){
return document.getElementById("ApplicationRoot").href;
}
使用base标签:
<head>
<base href="http://www.example.com/myapp/" />
</head>
从现在开始,此页面上使用的所有链接(包括 JavaScript 和 HTML 中的)都将相对于基准标签而言,该基准标签为 "http://www.example.com/myapp/"。
你还可以使用 asp.net 的 VirtualPathUtility
功能:
<script>
var basePath = '<%=VirtualPathUtility.ToAbsolutePath("~/")%>';
</script>
注意:我没有对路径进行编码为JSON字符串(转义引号、控制字符等)。我认为这不是一个大问题(例如,引号在URL中未经转义是不允许的),但谁也不能确定...
我通常在js文件的顶部创建一个变量,并将根路径分配给它。然后在引用文件时使用该变量。
var rootPath = "/";
image.src = rootPath + "images/something.png";
~/是应用程序的根目录,而不是字面上的根目录,它将解释~/为<YourAppVirtualDir>/
在JavaScript中,要使用字面上的根目录只需使用 / ,例如 "/root.html"。没有办法在JavaScript中获取应用程序级别的路径。
您可以在ASPX文件中进行修改,并在标记中输出它,但我建议考虑其安全性影响。
~/
最终会被展开,但这不会发生。 - LloydKamarey的答案可以改进,以支持动态基路径:
<head>
<base href="http://<%= Request.Url.Authority + Request.ApplicationPath%>/" />
</head>
<base href="http://@((Request.Url.Authority + Request.ApplicationPath).TrimEnd('/'))/" />
ApplicationPath有时以“ /”结尾,有时则没有,所以我添加了TrimEnd('/')调用。 - DanielC<script src="/assets/js/bootstrap.min.js"><script>
并使用Page.ResolveClientUrl,如下所示:
<script src='<%=ResolveClientUrl("~/assets/js/bootstrap.min.js")%>'></script>
function AppRoot() {
//
// Returns the root of the currently running ASP application.
// in the form: "http://localhost/TRMS40/"
//
// origin: "http://localhost"
// pathname: "/TRMS40/Test/Test%20EMA.aspx"
//
// usage:
// window.open( AppRoot() + "CertPlan_Editor.aspx?ID=" + ID);
//
var z = window.location.pathname.split('/');
return window.location.origin + "/" + z[1] + "/";
}
ASP.NET MVC应用程序的解决方案
在使用IIS和VS中的IIS Express时,此方法有效。
将此代码片段放置在所有脚本加载之前,以便具有根URL变量“approot”。
在脚本中可使用此服务:
<script>
var approot = "@Url.Content("~")";
</script>
--> other scripts go here or somewhere later in the page.
然后在您的脚本或页面脚本中使用它。 示例:
var sound_root_path = approot + "sound/";
var img_root_path = approot + "img/";
appproot变量的值可能是:
"/YourWebsiteName/" <-- IIS
或者只是:
"/" <-- IIS Express
protected override void
OnPreRender(EventArgs e) {
base.OnPreRender(e);
if (Page.Header != null)
{
//USED TO RESOLVE URL IN JAVASCRIPT
string baseUrl = String.Format("var baseUrl='{0}';\n",
HttpContext.Current.Request.ApplicationPath);
Page.Header.Controls.Add(new LiteralControl(String.Format(Consts.JS_TAG,
baseUrl)));
}
}
然后在你的全局JavaScript函数中添加以下内容:
function resolveUrl(url) {
if (url.indexOf("~/") == 0) {
url = baseUrl + url.substring(2);
}
return url; }
现在你可以像这样使用它:
document.getElementById('someimage').src = resolveUrl('~/images/protest.jpg');
对于一些小型项目来说可能有点过于繁琐,但对于完整的应用程序非常有效。