【问题标题】:getting data from controller in error function of jquery ajax -- Asp.net MVC在 jquery ajax 的错误函数中从控制器获取数据 - Asp.net MVC
【发布时间】:2015-05-23 07:17:01
【问题描述】:

我有一个像下面这样的 jquery ajax 脚本

    $.ajax({
            type: "POST",
            url: "Main/receive", // the method we are calling
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ 'p':$("#txtname").val() }),
            dataType: "json",
            success: function (result) {
                alert('Yay! It worked!');
                // Or if you are returning something

            },
            error: function (result) {
                alert('Oh no zzzz:('+result.responseText);
            }
        });

我正在调用 Controller 操作方法。数据正在发送到控制器的操作方法,我也从控制器接收数据。但是我收到的数据在 jquery ajax 的错误函数中。

我希望它在成功函数中。

为什么我的成功函数没有被调用。

以下是我的控制器的动作方法,

   [HttpPost]
    public string receive(string p)
    {
        ViewBag.name = p;
        return p;

    }

【问题讨论】:

  • 因为您已指定返回类型为 json(即dataType: "json",)。将服务器方法更改为return Json(p); 但是您的代码中有很多或其他潜在错误,所以我稍后会发布答案。
  • @StephenMuecke 谢谢,请不要忘记发布答案

标签: c# jquery .net ajax asp.net-mvc


【解决方案1】:

错误的原因是您已指定返回的数据类型为 json(在 dataType: "json", 行中),但您的方法返回文本。您有 2 个选项。

  1. 更改控制器方法以使用return Json(p);返回json
  2. 将 ajax 选项更改为 dataType: "text", 或直接省略它

但是您可以如下所述改进您的脚本

$.ajax({
  type: "POST",
  url: '@Url.Action("receive", "Main")', // don't hardcode url's
  data: { p: $("#txtname").val() }, // no need to stringify (delete the contentType: option)
  dataType: "json",
  success: function (result) {
      alert('Yay! It worked!');
  },
  error: function (result) {
      alert('Oh no zzzz:('+result.responseText);
  }
});

甚至更简单

$.post('@Url.Action("receive", "Main")', { p: $("#txtname").val() }, function(result) {
    alert('Yay! It worked!');
}).fail(function(result) {
    alert('Oh no zzzz:('+result.responseText);
});

注意:您应该始终使用@Url.Action() 来生成正确的url,在这种情况下不需要对数据进行字符串化(但您需要删除contentType: 行,因此它使用默认的application/x-www-form-urlencoded; charset=UTF-8

此外,这不是严格意义上的 POST(您不会更改服务器上的数据 - 但我认为这只是为了测试)。 ViewBag.name = p; 行没有任何意义 - 它在您的上下文中什么也不做,一旦您从该方法返回,ViewBag 无论如何都会丢失。

【讨论】:

  • 我在error 行中有错字 - 请参阅编辑,但该错误没有意义(我在项目中测试了代码,它工作正常)。我会看看是否能找到有关该错误的一些信息
  • 我问了一个新问题。你能看看吗?stackoverflow.com/questions/30420765/…
【解决方案2】:

尝试如下更改你的控制器代码

[HttpPost]
 public ActionResult List(string p)
    {
       ViewBag.name = p;
       return Json(ViewBag);
    }

【讨论】:

  • 它给出了错误。无法将 p 字符串转换为类型对象
【解决方案3】:

您的控制器方法应如下所示:

[HttpPost]
public ActionResult receive(string p)
{
   return Json(p);
}

【讨论】:

    猜你喜欢
    • 2013-05-08
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多