c# - jQuery $.ajax 成功不从 JsonResult 触发

标签 c# asp.net-mvc jquery

我的代码进行 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/

相关文章:

c# - 将文件夹重命名命令发送到 Windows 资源管理器

c# - 将数据插入 Excel

c# - ASP.NET MVC : Why Range Data Annotation is not working on checkbox in client side?

asp.net-mvc - 使用 FileStreamResult 删除临时文件

c# - 使用 ASP.net MVC 执行提交(回发)和重定向

jquery - 出现 "Scripts may close only the windows that were opened by it"错误

c# - 在 WPF 中,您可以在没有代码隐藏的情况下过滤 CollectionViewSource 吗?

c# - 使用 Mono.Cecil 通过 dll 获取静态只读字符串值?

php - 使用 PHP 和 jquery 下载文件时显示下载进度

javascript - 如何在 ajax 成功时获取 TreeView 中的复选框计数值?