Gra*_*ton 7 asp.net-mvc jquery
在我的ASP.NET MVC项目中使用JQuery调用时,我遇到了一个奇怪的问题.我发现Ajax调用给出404(资源未找到错误).但是当我使用通常的URL GET调用时,我可以毫无问题地成功调用服务器.知道为什么会这样吗?
这是我的ASP.NET MVC代码
public class ViewRecordController: Controller
{
public JSONResult GetSoftwareChoice(string username)
{
return Json(username);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的JQuery代码:
$(function() {
$("#username").click(function() {
$.getJSON("ViewRecord/GetSoftwareChoice", {username:'123'},
function(data) {
alert(data);
});
});
});
Run Code Online (Sandbox Code Playgroud)
上面的JQuery给了我404错误.ViewRecord/GetSoftwareChoice就AJAX调用而言,显然在服务器上找不到.
但是,如果我在我的网络浏览器中输入:
http://myapp/ViewRecord/GetSoftwareChoice?username=123
Run Code Online (Sandbox Code Playgroud)
那没有问题.
事实上,这非常奇怪.
如果您有兴趣,以下是我的路线:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
Run Code Online (Sandbox Code Playgroud)
编辑:我进入我的代码,发现URL调用ViewRecord/GetSoftwareChoice?username=123.
您可能想尝试使用UrlHelper,而不是对网址进行硬编码:
$(function() {
$("#username").click(function() {
var url = '<%= UrlHelper.Action("GetSoftwareChoice", "ViewRecord") %>';
$.getJSON(url, {username: '123'}, function(data) {
alert(data);
});
});
});
Run Code Online (Sandbox Code Playgroud)
我通过使用FireBug向我展示由JQuery生成的请求来解决此问题.令我惊讶的是,生成的网址是
http://localhost/ViewRecord/ViewRecord/GetSoftwareChoice?username=123
Run Code Online (Sandbox Code Playgroud)
对于JSON调用:
$(function() {
$("#username").click(function() {
$.getJSON("ViewRecord/GetSoftwareChoice", {username:'123'},
function(data) {
alert(data);
});
});
});
Run Code Online (Sandbox Code Playgroud)
所以我只需将$.getJSON线路更改为
$.getJSON("GetSoftwareChoice", {username:'123'},
Run Code Online (Sandbox Code Playgroud)
或者,使用正斜杠:
$.getJSON("/ViewRecord/GetSoftwareChoice", {username:'123'},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30852 次 |
| 最近记录: |