使用jQuery.get时,我可以指定相关的URL? [英] Can I specify relative URL when using jQuery.get?
问题描述
我试图让Ajax调用,像这样:
I'm trying to make an ajax call like so:
$.get('/home/myInfo', function (data)
{
....
});
的http://本地主机/ MyApp的/家庭/指数< 我是从一个网页,在调用它/ A> I'm calling it from a page that is at: http://localhost/myapp/home/index 当我试图让上面的调用,它进入:的http://本地主机/ MyApp的/家庭/指数/家庭/ MyInfo的 When I try to make the above call, it goes to: http://localhost/myapp/home/index/home/myInfo 我想它去的http://本地主机/ MyApp的/家庭/ 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: 如果这是一个单独的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: 和则: 或者如果你是一个AJAXifying形式或锚: or if you are AJAXifying a form or an anchor: 在这里当然会一直使用助手产生锚: where the anchor would of course have been generated using helpers: 看到了吗?无需辛苦code的URL。不这样做,因为它会在打破非常第二你修改你的路由的格局 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 这篇关于使用jQuery.get时,我可以指定相关的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!推荐答案
$.get('@Url.Action("MyInfo", "Home")', function (data) {
....
});
<div id="mydiv" data-url="@Url.Action("MyInfo", "Home")">Click me</div>
$('#mydiv').click(function() {
$.get($(this).data('url'), function (data) {
....
});
});
$('#myanchor').click(function() {
$.get(this.href, function (data) {
....
});
return false;
});
@Html.ActionLink("click me", "MyInfo", "Home", null, new { id = "myanchor" })
的Global.asax
。按照此方法的code将完全不可知的你的路由结构的任何更改。Global.asax
. By following this technique your code will be totally agnostic to any changes of the structure of your routes.