JQuery Post Call 中的相对 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18338042/
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
Relative URL in JQuery Post Call
提问by SerenityNow
I have the following situation.
我有以下情况。
I developed my first MVC Asp.Net application. it runs on my server at the following adress
我开发了我的第一个 MVC Asp.Net 应用程序。它在我的服务器上运行在以下地址
http://localhost:59441/
I wrote some JQuery Post Methods that looked like this
我写了一些看起来像这样的 JQuery Post 方法
$.ajax({
type: "POST",
url: "/CeduleGlobale/UpdateCheckBox", ...
CeduleGlobale is my ControllerName and UpdateCheckBox is my methodName
CeduleGlobale 是我的 ControllerName 和 UpdateCheckBox 是我的 methodName
When I put the Application on the testServer, it was put in a VirtualDirectory
当我将应用程序放在 testServer 上时,它被放在一个 VirtualDirectory 中
hence the application is now
因此应用程序现在是
http://testServer/JprApplication/
no more port to specify and also an application Name
不再需要指定端口和应用程序名称
When I started to test, I quickly noticed my JQuery Post calls didn't work anymore...
当我开始测试时,我很快注意到我的 JQuery Post 调用不再起作用了......
I modified them so now the URL is
我修改了它们,所以现在 URL 是
/JprMvc/CeduleGlobale/UpdateCheckBox
the problem is 2 fold.
问题是2倍。
- this makes it hard to test on my development machine because IIS Express doesn't allow me to specify a virtual Directory.
- I don't like hardCoding the Virtual Directory Name in the JQuery because I dont know what name the Application will have in the production environment and therefore i will have to modify my script before i can install the application in production.
- 这使得我很难在我的开发机器上进行测试,因为 IIS Express 不允许我指定一个虚拟目录。
- 我不喜欢在 JQuery 中硬编码虚拟目录名称,因为我不知道应用程序在生产环境中的名称,因此我必须修改我的脚本,然后才能在生产环境中安装应用程序。
I am sure I am missing some basic thing to simplify this.
我确定我缺少一些基本的东西来简化这个。
Thanks
谢谢
回答by Tommy
Depending on where you actually have your JavaScript located (inside the View or a separate JS file), you have a couple of options.
根据您实际放置 JavaScript 的位置(在视图中或单独的 JS 文件中),您有多种选择。
Option 1 - Inside the View
选项 1 - 在视图内
Simply use the Html Helpers to generate the links for you
只需使用 Html Helpers 为您生成链接
<script type="text/javascript">
$(function(){
$.ajax({
type: "POST",
url: "@Url.Action("UpdateCheckBox", "CeduleGlobale")"
});
});
</script>
Option 2 - Standalone JS File
选项 2 - 独立 JS 文件
We typically have a function per page that sets up that page's handlers. So, we can do something like the following:
我们通常为每个页面设置一个函数来设置该页面的处理程序。因此,我们可以执行以下操作:
View
看法
<script type="text/javascript">
$(function(){
SetOrderPage('@Url.Action("UpdateCheckBox", "CeduleGlobale")');
});
</script>
Standalone JS File
独立的 JS 文件
function SetOrderPage(ajaxPostUrl){
$.ajax({
type: "POST",
url: ajaxPostUrl
)};
}
Option 3 - Standalone JS file Method 2
选项 3 - 独立 JS 文件方法 2
You could have a global variable in your in your JS file that is the siteroot. The draw back here is that you will need to hand create each of your action method paths. On each page, you could set the site root global variable as such:
您的 JS 文件中可以有一个全局变量,即站点根。这里的缺点是您需要手动创建每个操作方法路径。在每个页面上,您可以这样设置站点根全局变量:
Standalone JS File
独立的 JS 文件
var siteRoot;
View
看法
<script type="text/javascript">
siteRoot = '@Request.ApplicationPath';
</script>
Keep in mind you cannot use Razor syntax in a stand alone JS file. I believe that it is best to let Razor/MVC/.NET dynamically give you the site path or URL route as it will really cut down on the mistakes that could be made when moving between sites/virtual directories.
请记住,您不能在独立的 JS 文件中使用 Razor 语法。我相信最好让 Razor/MVC/.NET 动态地为您提供站点路径或 URL 路由,因为它会真正减少在站点/虚拟目录之间移动时可能发生的错误。
回答by Rob Schmuecker
As far as I know there is no other way around this. Unless you are willing to user relative URL's i.e:
据我所知,没有其他办法可以解决这个问题。除非您愿意使用相对 URL,即:
$.ajax({
type: "POST",
url: "./CeduleGlobale/UpdateCheckBox", ...
But that can get messy for various reasons when you refactor code. Alternatively prepend the URL which is globally defined and therefore you then only need to change it in once place before going to production.
但是当您重构代码时,由于各种原因,这可能会变得混乱。或者,在全局定义的 URL 前面加上,因此您只需要在开始生产之前在一次位置更改它。
i.e.
IE
//Globally defined serverRoot
serverRoot = "http://someaddress/somevirtualdirectory";
$.ajax({
type: "POST",
url: serverRoot + "/CeduleGlobale/UpdateCheckBox", ...
That way if you don't need it you can just set serverRoot = '';
and all will be back to how it is now.
这样,如果您不需要它,您只需设置即可serverRoot = '';
,一切都会恢复到现在的状态。
回答by RizzCandy
I had this kind issue on MVC 5 using JQuery, so I went to this solution that gets rid of the problem when you are in Localhost, and in any Navigator even when you're deploying app in a subfolder.
我在使用 JQuery 的 MVC 5 上遇到了这种问题,所以我去了这个解决方案,当你在本地主机和任何导航器中时,即使你在子文件夹中部署应用程序,它也能解决这个问题。
var pathname = window.location.pathname;
var VirtualDirectory;
if (pathname.indexOf("localhost") >= 0 && pathname.indexOf(":") >= 0) {
VirtualDirectory = "";
}
else {
if ((pathname.lastIndexOf('/')) === pathname.length + 1) {
VirtualDirectory = pathname.substring(pathname.indexOf('/'), pathname.lastIndexOf('/'));
} else {
VirtualDirectory = pathname;
}
}
And then in any ajax call :
然后在任何 ajax 调用中:
$.post(VirtualDirectory + "/Controller/Action", { data: data}, "html")
.done(function (result) {
//some code
});
回答by Codersjunto
Pass @Url.Action("action","controller") to the javascript from the view. This will allow it to be update dynamically at run time.
从视图中将 @Url.Action("action","controller") 传递给 javascript。这将允许它在运行时动态更新。
<script>
myJavascriptfunction(@Url.Action("action","controller"),param1,param2);
</script>
There may be a function to get the root path also which you could use to initialize the root variables in the previous answers.
可能还有一个获取根路径的函数,您可以使用它来初始化先前答案中的根变量。
回答by Sampath Dilhan
I know this is an old post. But, I had the same issue and ended up here. And managed to fix that issue with UrlHelper.Actionmethod. It should be used something like this. (Note that this specific solution will works within the view.)
我知道这是一个旧帖子。但是,我遇到了同样的问题并最终到了这里。并设法使用UrlHelper.Action方法解决了该问题 。它应该像这样使用。(请注意,此特定解决方案将在视图中起作用。)
url: "@Url.Action("UpdateCheckBox", "CeduleGlobale")",
Hope this helps. :)
希望这可以帮助。:)
回答by kudzai zishumba
http://localhost:59441/
andhttp://testServer/JprApplication/
will both work with your
http://localhost:59441/
并且http://testServer/JprApplication/
都将与您的
$.ajax({
type: "POST",
url: "/CeduleGlobale/UpdateCheckBox", ...
$.ajax({
type: "POST",
url: "/CeduleGlobale/UpdateCheckBox", ...
if your hosting in iis you just need to create a virtual host in yourC:\Windows\System32\drivers\etc\hosts
如果您在 iis 中托管,您只需要在您的主机中创建一个虚拟主机C:\Windows\System32\drivers\etc\hosts
file. Add this line at the bottom of your hosts file
文件。在 hosts 文件底部添加这一行
127.0.0.1 CeduleGlobale
127.0.0.1 CeduleGlobale
create a new site like this select sites, right click and create a new site
fill in your details and set the same hostname as you created above 'CeduleGlobale'
填写您的详细信息并设置与您在“CeduleGlobale”上方创建的相同的主机名
then deploy your mvc appliation to this site
然后将您的 mvc 应用程序部署到此站点
回答by HockeyJ
@Tommy's answer was a great pointer, however for .NET CoreI had to do things a little differently, as the Request
object has different properties.
@Tommy 的回答是一个很好的指针,但是对于.NET Core,我必须做一些不同的事情,因为Request
对象具有不同的属性。
Things were made more tricky by deploying to a virtual directory but using IIS Express for development; hence the if
statement when setting the base url.
通过部署到虚拟目录但使用 IIS Express 进行开发,事情变得更加棘手;因此if
设置基本网址时的声明。
Shared/_Layout.cshtml
共享/_Layout.cshtml
<!-- Set the site root for javascript in _Layout.cshtml.-->
@if (!String.IsNullOrWhiteSpace(@Context.Request.PathBase.Value))
{
/* LIVE - includes virtual directory */
<script>
window.siteRoot = "@Context.Request.Scheme" + "://" + "@Context.Request.Host.Value" + "@Context.Request.PathBase.Value" + "/";
</script>
}
else
{
/* DEBUG - no virutal directory, e.g. IIS Express */
<script>
window.siteRoot = "@Context.Request.Scheme" + "://" + "@Context.Request.Host.Value" + "/";
</script>
}
Then from any JavaScript file
然后从任何 JavaScript 文件
/* from any javascript file */
var url = window.siteRoot + 'MySearch/GetMySearchResults';
$.ajax({
url: url,
type: 'GET',
cache: false,
data: searchObj,
success: function (result) {
alert('yatta!');
},
fail: function (e, k, n) {
alert('hmph!');
},
done: function() {
// hide spinner
}
});
Obviously you might wish to create your own namespace or something to save pollutingwindow
. I've tried to keep the example below as simple as possible.
显然,您可能希望创建自己的命名空间或其他东西来减少污染window
。我试图让下面的例子尽可能简单。