问题描述
我试图让Ajax调用,像这样:
I'm trying to make an ajax call like so:
$.get('/home/myInfo', function (data)
{
....
});
When I try to make the above call, it goes to: http://localhost/myapp/home/index/home/myInfo
我想它去
我必须指定绝对URL?
Do I have to specify absolute URL?
推荐答案
绝对不会硬code网址,这样在ASP.NET MVC应用程序。使用URL处理时,必须使用网址帮手,就像这样:
Absolutely never hardcode urls like this in an ASP.NET MVC application. Always use URL helpers when dealing with urls, like this:
$.get('@Url.Action("MyInfo", "Home")', function (data) {
....
});
如果这是一个单独的JavaScript文件,你不能使用服务器端的助手,以及例如,你可以使用HTML 5的一些DOM元素上数据 - *属性TAT你AJAXifying,像一个div或东西:
or if this is in a separate javascript file where you cannot use server side helpers, well you could for example use HTML 5 data-* attributes on some DOM element tat you are AJAXifying, like a div or something:
<div id="mydiv" data-url="@Url.Action("MyInfo", "Home")">Click me</div>
和则:
$('#mydiv').click(function() {
$.get($(this).data('url'), function (data) {
....
});
});
或者如果你是一个AJAXifying形式或锚:
or if you are AJAXifying a form or an anchor:
$('#myanchor').click(function() {
$.get(this.href, function (data) {
....
});
return false;
});
在这里当然会一直使用助手产生锚:
where the anchor would of course have been generated using helpers:
@Html.ActionLink("click me", "MyInfo", "Home", null, new { id = "myanchor" })
看到了吗?无需辛苦code的URL。不这样做,因为它会在打破非常第二你修改你的路由的格局的Global.asax
。按照此方法的code将完全不可知的你的路由结构的任何更改。
See? No need to hardcode urls. Don't do it as it will break at the very second you modify the pattern of your routes in Global.asax
. By following this technique your code will be totally agnostic to any changes of the structure of your routes.
这篇关于使用jQuery.get时,我可以指定相关的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!