Rails:如何抓住ajax的成功

Rails: How to catch ajax success

本文关键字:成功 ajax 何抓住 Rails      更新时间:2023-09-26

我在谷歌上搜索了很多,但都找不到我的错误。因为我刚开始使用JS,所以这可能很容易。使用:Rails 4

我有一个带有表单的模态,我想在成功(或不成功)完成ajax调用后做一些事情。现在只是关闭模态。

modal(这确实有效,所以我可以编辑东西):

.modal.fade{ id: attribute.id, role: 'dialog', tabindex:'-1' }
  .modal-dialog{ role: 'document'}
    .modal-content
      .modal-header
        %button{ type: 'button', class: 'close', 'data-dismiss' => "modal" }
          %span ×
        %h4.modal-title= attribute.name
  = form_for attribute, remote: true, html: { class: 'form-inline', id: 'edit_form' } do |f|
    .modal-body
      .form-group
        = f.label :name, 'Name', class: 'form-label', style: 'width: 150px'
        = f.text_field :name, class: 'form-control', style: 'width:200px;margin-right: 35px'
    .modal-footer
      %button{ type: "button", class: "btn btn-default pull-left", 'data-dismiss' => "modal" }
        Close
      = f.submit 'Create', class: 'btn btn-primary pull-right'

我的JS文件(别笑):

$(document).ready( function($) {
        console.log('ready'); # this I *can* see in the console
    $('#edit_form').bind("ajax:success", function() {
      console.log('great success') # this I *can't* see in the console.
    });
});

控制器(另一个有趣的事实:模态是在另一个控制器的视图中触发的,而不是我实际试图改变的模态):

respond_to do |format|
  format.js {}
end

所以最后,我想抓住"错误"answers"成功"的回调,并用它做点什么(这是我首先想弄清楚的)。我在这里做错了什么?

非常感谢你的帮助,真的很感激!

根据您可能想要尝试的类似问题的答案:

$('#edit_form').on("ajax:success", ...
//             ^-- instead of .bind

我想您也有一个最新的jQuery版本,所以尝试一下这个更改。