从Rails服务器通过AJAX返回的JSON运行失败

JSON Returned From Rails Server via AJAX fails to run

本文关键字:JSON 运行 失败 返回 AJAX Rails 服务器      更新时间:2023-09-26

我有一个简单的ajax post到服务器..

$(".invite-team-members-submit-btn").click(function() {
  $.post("invite_team_member", { 
    token: $("#token").val(), 
    email: $("#email").val(), 
    team: $("#team").val() 
  },"json")
    .done(function (responseText) {
      alert(responseText.response);
    })
    .fail(function (xhr,status,message) { alert("ERROR: " + message); })
    .then(function () { alert("Something should happen."); });
});

返回的JSON看起来像这样…

{"response":"Person has been invited."}

我的响应头在控制台中看起来像这样…

Response Headers
  Cache-Control max-age=0, private, must-revalidate
  Connection    close
  Content-Type  application/json; charset=utf-8
  Date  Wed, 22 May 2013 21:45:07 GMT
  Etag  "e5b5e12acbcc78372b2a861027b66c05"
  Status    200 OK
  Transfer-Encoding chunked
  X-Request-Id  d835ce021eff7733d67ebfcdd468bdf2
  X-Runtime 0.007909
  x-ua-compatible   IE=Edge

我的控制台不仅告诉我我收到了一个200状态,而且我的响应包含我想要的JSON。但是,在处理解析后的JSON时,不会发出警报。请注意,我没有收到警报,甚至没有从然后的功能。是什么原因造成的呢?

这很可能是由于jQuery在成功回调之前自动为您解析json。要使其始终发生,以便您可以始终期望它,请使用:

$(".invite-team-members-submit-btn").click(function() {
  $.post("invite_team_member", { 
    token: $("#token").val(), 
    email: $("#email").val(), 
    team: $("#team").val() 
  },"json")
    .done(function (responseText) {
      alert(responseText.response);
    })
    .fail(function (xhr,status,message) { alert("ERROR: " + message); })
    .then(function () { alert("Something should happen."); });
});

注意第2行末尾的"json"参数

Update$.post()的末尾有一个;,使得.done.fail.then失效。修复了上面的代码。

如果您仍然没有看到完成警报或失败警报,那么您的控制台中存在错误或单击事件没有发生。如果使用Firefox,请确保您也使用firebug。