jQuery ajax:即使响应正常,错误也会运行200

时间:2012-05-31 19:09:17

标签: javascript ajax ruby-on-rails-3 jquery

我有一个表单,通过AJAX提交表单:remote =>真正。查看服务器日志和FireBug,我得到200 OK的响应,它以下列形式返回JSON:

{ "email": "test@test.com"}

然后我有这两个处理程序:

$('#new_invitation').bind("ajax:success", function(event, data, status, xhr) {
    alert('test');
});

$('#new_invitation').bind("ajax:error", function() {
    alert('error');
});

即使我回到200OK,它也会触发错误处理程序。我设法让成功处理程序工作的唯一一次是我在标题中发送一个空的响应200。

我无法弄清楚为什么这不起作用:-S

编辑1 ------------ 完成这些更改后:

$('#new_invitation').bind("ajaxSuccess", function(event, data, status, xhr) {
    alert('test');
});

$('#new_invitation').bind("ajaxError", function(jqXHR, textStatus, errorThrown) {
alert('error');
    console.log(jqXHR.responseText);
    console.log(textStatus.responseText);
    console.log(errorThrown.responseText);
});

我仍然遇到同样的错误。日志的东西给了我:

undefined
my_email@test.com
undefined

以下是表单的代码(标准Rails的东西):

<%= form_for @shoot.invitations.new, :url=>shoot_invitations_path(@shoot), :remote => true, :html => {:class => 'form-inline'} do |f| %>
    <%= f.text_field :email, :'placeholder' => 'ex: test@test.com' %>
    <%= f.text_field :role, :'placeholder' => 'ex: Photographer' %>
    <%= f.submit "Invite", :class => 'btn btn-success' %>
<% end %>

编辑2 ---------

我做了一些更改,现在看来我的错误是解析错误。我不明白,因为这是我从服务器(data.responseText)回来的JSON,这似乎都很好:

{"email":"zxxczxc@test.com"}

答案--------- 当我提出时,我设法让一切正常:'data-type'=&gt; :json在表单选项中。我之前尝试过这个并没有用,因为我把它放在form_tag选项而不是html选项......

5 个答案:

答案 0 :(得分:18)

如果服务器返回一些无效的JSON,例如单个空格,jQuery将生成一个解析错误,即使状态代码为200,也会认为它是一个失败的请求。

从jQuery 1.9开始,当类型设置为JSON时,完全空的响应被视为失败的请求,因为空字符串是无效的JSON。请参阅http://jquery.com/upgrade-guide/1.9/#jquery-ajax-returning-a-json-result-of-an-empty-string

答案 1 :(得分:8)

  1. 检查$ .ajax的数据类型是否设置为jsonp

  2. 尝试返回{email:“ahsgah@ahsgh.com”}

答案 2 :(得分:2)

JSON.parse('')抛出错误。对我来说,这是愚蠢的,它应该返回undefined。 我将此代码添加到我的应用

#HACK JSON.parse('') should return undefined, not throw an error
_parse = JSON.parse
JSON.parse = (str) =>
  unless str == ''
    _parse.apply JSON, arguments

或者对于那些不使用coffeescript(未经测试)的穷人

//HACK JSON.parse('') should return undefined, not throw an error
var _parse = JSON.parse
JSON.parse = function(str) {
  if (str !== '')
    return _parse.apply(JSON, arguments);
  else
    return undefined;
}

答案 3 :(得分:1)

使用ajaxSuccess代替ajax:success,使用ajaxError代替ajax:error作为您的eventTypes。

见这里:http://docs.jquery.com/Ajax_Events

答案 4 :(得分:0)

(在Rails 5.2和jQuery 2上),我花了一个小时并排比较两个UJS代码,但无济于事:都返回了类似格式的Javascript函数调用(以更新前端),以及一个状态(共200个),但一个触发View,而另一个则不触发。通过将 application.js 清单中的 jquery_ujs 切换为 rails-ujs ,我能够解决该问题:

ajax:error

请注意连字符VS下划线!

现在,两个调用的行为方式相同(正确)。我希望这对其他人有帮助。