gpt4 book ai didi

javascript - 如何在 MVC 应用程序中解析来自 JavaScript 的相对路径

转载 作者:行者123 更新时间:2023-11-30 09:54:32 26 4
gpt4 key购买 nike

这是我试图从 .js 文件中获取的 url,其中包含与 knockout 相关的函数:

self.followAction = $.resolvePath("/People/Follow?uid="+ data.UserId);这里 People 是 Controller ,Follow 是操作方法,点击按钮时,我想发送 userId,所以我写了这个。

为了从 javascript 中解析相对路径,我编写了这个函数

// Fix for resolving relative paths from within js scripts
$.resolvePath = function(url)
{
var path = '@Request.ApplicationPath';
if (path != '/') return path + url;
return url;
};

但是,在单击按钮时,我收到此错误:HTTP 错误 404.0 - 未找到它正在尝试的网址是:

localhost:44305/People/@Request.ApplicationPath/People/Follow?uid=8

我了解到 razor 代码不会在 js 文件中解释。所以,我把这个函数放在一个局部 View 中:

   $.resolvePath = function(url)
{
var path = '@Request.ApplicationPath';
if (path != '/') return path + url;
return url;
};

我试过像这样在布局头部的部分直接调用它:

 <head>
<script src="~/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
@{ Html.RenderPartial("VirtualPathFix"); }
</head>

但随后开始显示错误:

 $.resolveurl: function is not defined

如果我将此函数直接放在脚本文件夹中的 people.js 文件中,则不会出现错误,但随后单击跟随按钮时,传递 url 的 http 404 错误是:

 localhost:44305/People/@Request.ApplicationPath/People/Follow?uid=8

谁能帮帮我。感觉迷路了

我尝试按照 darin 的建议在 View 页面的标题中使用 window.baseUrl:

   <script type="text/javascript">
window.baseUrl = '@Url.Content("~/")';
</script>

但是我的 people.js 文件无法获取此属性,所以错误是:

Uncaught TypeError: window.baseUrl is not a function on line18 in people.js file. Can anyone tell me what are other things to try.

最佳答案

您可以在 Razor 模板中准备此 url:

<head>
<script type="text/javascript">
window.baseUrl = '@Url.Content("~/")';
</script>
</head>

现在在你的 js 文件中你可以使用这个变量 window.baseUrl 你不再需要这个 $.resolvePath 函数。

关于javascript - 如何在 MVC 应用程序中解析来自 JavaScript 的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34653558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com