我的代码进行 ajax 调用:
$.ajax({
url: "/Controller/EmailUserKeys",
dataType: 'json',
success: function () {
alert('success');
},
error: function () {
alert('error');
}
});
它在我的 Controller 中调用一个返回一些 JSON 的操作:
public JsonResult EmailUserKeys(string UserId)
{
...
return Json(new { success = true });
}
我的问题是调用了 ajax 错误函数而不是 ajax 成功函数。
为什么?
附言。如果我的操作返回“return null;”,就会调用 ajax 成功函数。
最佳答案
您必须允许返回 JSON 结果时默认禁用的 GET:
public JsonResult EmailUserKeys(string UserId)
{
...
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
或者使用 POST 请求:
$.ajax({
url: "/Controller/EmailUserKeys",
type: "POST",
dataType: 'json',
data: { userId: 'some user id' },
success: function () {
alert('success');
},
error: function () {
alert('error');
}
});
也永远不要像您那样将 url 硬编码到您的 Controller 操作中。在 ASP.NET MVC 应用程序中处理 url 时始终使用 url 帮助程序:
url: "@Url.Action("EmailUserKeys", "Controller")",
还有一条建议:使用 javascript 调试工具,例如 FireBug如果您正在进行任何网络开发。除了其他有用的功能外,它还允许您检查 AJAX 请求。如果您使用过它,您会看到服务器发送的响应如下所示:
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
而且您不需要到 StackOverflow 上来问这个问题,因为您已经知道答案了。
关于c# - jQuery $.ajax 成功不从 JsonResult 触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12067143/