简体   繁体   English

〜/ javascript中的等价物

[英]~/ equivalent in javascript

做一个“根”的任何聪明的办法基于路径在JavaScript中引用,只是我们已经在路上~/在ASP.NET?

Have your page generate a tag with something like: 让您的网页生成标记,例如:

<link rel="home" id="ApplicationRoot" href="http://www.example.com/appRoot/" />

Then, have a function in JavaScript that extracts the value such as: 然后,在JavaScript中有一个提取值的函数,例如:

function getHome(){
    return document.getElementById("ApplicationRoot").href;
}

Use base tag: 使用基本标签:

<head>
   <base href="http://www.example.com/myapp/" />
</head>

... ...

from now any link use on this page, no matter in javascript or html, will be relative to the base tag, which is " http://www.example.com/myapp/ ". 从现在开始,无论是在javascript还是html中,此页面上的任何链接都将使用相对于基本标记,即“ http://www.example.com/myapp/ ”。

You could also use the asp.net feature VirtualPathUtility : 您还可以使用asp.net功能VirtualPathUtility

<script>
var basePath = '<%=VirtualPathUtility.ToAbsolutePath("~/")%>';
</script>

Notice: I don't encode the path to a JSON -string (escape quotes, control characters etc). 注意:我没有将路径编码为JSON -string(转义引号,控制字符等)。 I don't think this is a big deal (quotes for example aren't allowed unescaped in an URL), but one never knows... 我不认为这是一个大问题(例如,引号不允许在URL中转义),但是人们从不知道......

I usually create a variable at the top of the js file and assign it the root path. 我通常在js文件的顶部创建一个变量并为其分配根路径。 Then I use that variable when referencing a file. 然后我在引用文件时使用该变量。

var rootPath = "/";
image.src = rootPath + "images/something.png";

Kamarey's answer can be improved to support a dynamic base path: 可以改进Kamarey的答案以支持动态基本路径:

<head>    
      <base href="http://<%= Request.Url.Authority + Request.ApplicationPath%>/" />    
</head> 

This will ensure a correct root path regardless of deployment configuration. 无论部署配置如何,这都将确保正确的根路径。

To be fair, this doesn't answer the original question, but it elimiates most needs for getting the root path from javascript. 公平地说,这不能回答原始问题,但它消除了从javascript获取根路径的大多数需求。 Simply use relative URL's everywhere, without prefixing with slash. 只需在任何地方使用相对URL,而不使用斜杠作为前缀。

Should you still need to access it from javascript, add an id attribute and use document.getElementFromId() as MiffTheFox suggested - but on the base-tag. 如果你仍然需要从javascript访问它,添加一个id属性并使用document.getElementFromId()作为MiffTheFox建议 - 但在base-tag上。

~/ is the application root and not a literal root, it interpets ~/ to mean <YourAppVirtualDir>/ 〜/是应用程序根,而不是文字根,它<YourAppVirtualDir>/ 〜/表示<YourAppVirtualDir>/

To do a literal root in JavaScript it's just /, ie "/root.html". 要在JavaScript中创建一个字面根,它只是/,即“/root.html”。 There's no way of getting an application level path like that in JavaScript. 在JavaScript中无法获得类似于应用程序级别的路径。

You could hack it in the ASPX file and output it in a tag but I would consider the security implications of that. 您可以在ASPX文件中破解它并将其输出到标记中,但我会考虑其安全含义。

Another option that's a bit simpler and more universal would be to take the following: 另一个更简单,更普遍的选择是采取以下措施:

<script src="/assets/js/bootstrap.min.js"><script>

and use Page.ResolveClientUrl like so: 并使用Page.ResolveClientUrl,如下所示:

<script src='<%=ResolveClientUrl("~/assets/js/bootstrap.min.js")%>'></script>

then regardless of what subdirectory the urls will always be rendered correctly. 然后无论哪个子目录都将始终正确呈现网址。

The following function will calculate the root of the currently running application. 以下函数将计算当前运行的应用程序的根目录。 I use it to locate the absolute location of resources, when called from somewhere deep within the application tree. 当从应用程序树深处的某个地方调用时,我用它来定位资源的绝对位置。

    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] + "/";
    }

Solution for ASP.NET MVC applications ASP.NET MVC应用程序的解决方案

This works when using IIS and also IIS Express in VS. 这在VS中使用IIS和IIS Express时也适用。

Put this snippet before all scripts load, in order to have the root url variable "approot". 在加载所有脚本之前放置此代码段,以使根URL变量“approot”。

at your service in the scripts: 在您的脚本服务:

<script>
        var approot = "@Url.Content("~")";
</script>

 --> other scripts go here or somewhere later in the page.

Then use it in your script or page script. 然后在脚本或页面脚本中使用它。 Example: 例:

var sound_root_path = approot + "sound/";
var img_root_path = approot + "img/";

the approot variable will be something either: approot变量将是:

"/YourWebsiteName/" <-- IIS “/ YourWebsiteName /”< - IIS

or just: 要不就:

"/" <-- IIS Express “/”< - IIS Express

In the PreRender of your .NET base page, add this: 在.NET基页的PreRender中,添加以下内容:

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

Then in your global JavaScript function, add the following: 然后在您的全局JavaScript函数中添加以下内容:

 function resolveUrl(url) {
   if (url.indexOf("~/") == 0) {
     url = baseUrl + url.substring(2);
   }
 return url; }

Now you can use it like this: 现在您可以像这样使用它:

 document.getElementById('someimage').src = resolveUrl('~/images/protest.jpg');

May be a little much for some projects, but works great for full fledged applications. 对于某些项目可能有点多,但对于完整的应用程序非常有用。

For ASP.net MVC Razor pages, Create a base tag like below in the <Head> tag 对于ASP.net MVC Razor页面,在<Head>标记中创建如下所示的基本标记

<base href="http://@Request.Url.Authority@Request.ApplicationPath" />

and in all your relative javascript URLs, make sure to start without a slash(/) otherwise it will refer from the root. 并且在所有相关的JavaScript URL中,确保没有斜杠(/),否则它将从根引用。

For ex. 对于前者 create all your urls like 创建你的所有网址

"riskInfo": { url: "Content/images/RiskInfo.png", id: "RI" },

or 要么

$http.POST("Account/GetModelList", this, request, this.bindModelList);

If you want to use it in HTML Still you can use ~, see this 如果你想在HTML中使用它仍然可以使用〜,请看这个

 href = @Url.Content("~/controllername/actionName")

See the check box click event in my MVC Application 请参阅我的MVC应用程序中的复选框单击事件

@Html.CheckBoxFor(m=>Model.IsChecked,  
   new {@onclick=@Url.Content("~/controller/action("+ @Model.Id + ", 1)"), 
   @title="Select To Renew" })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM