0

在我的 account.js.coffee 上,我有这个来查看是否调用了 Ajax 事件。

$(document).on 'ajax:success', 'form', (event) ->
 console.log 'success'

$(document).on 'ajax:error', 'form', (event) ->
 console.log 'error'
class AccountsController < ApplicationController
 def update
    respond_to do |format|
       if @account.update(home_params)
            format.html { redirect_to @account, notice: 'Home was successfully updated.' }
            format.json { render :show, status: :ok, location: @account }
            format.js
        else
            format.html { render :edit }
            format.json { render json: @account.errors, status: :unprocessable_entity }
            format.js
        end
    end
 end

结尾

当我远程提交我的表单时,应该触发一个 Ajax 事件,如果有错误应该触发 Ajax 错误,或者当对象被更新时触发 Ajax:success; 但是当表单出现错误时触发Ajax成功(当属性必须存在时为空属性),并且当对象成功更新时不会触发Ajax。该表单具有 remote:true 属性,并且在 application.js.coffee 上我有 jQuery、rails-ujs。我收到 ajax:error 事件的唯一一次是我故意从 update.js.erb 页面中删除对象以查看 Ajax:error 是否被触发。当 rails 在 4.2 上(更新之前)一切正常:(

这是我在表单上出现错误时在控制台上收到的事件。CustomEvent {isTrusted: false, detail: Array, initCustomEvent: function, type: "ajax:success", target: , ...}

更新.js.erb

<% if @account.errors.any? %>
    <!-- Show errors in to the modal view -->
    <%= render :partial=>'layouts/js_errors', :locals=> { :target=> @account } %>

    <!-- Sending error alert -->
    $('#flash-alerts').html("<div class=\"alert alert-danger\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"><i class=\"ace-icon fa fa-times\"></i></button><i class=\"ace-icon fa fa-check green\"></i>Something went wrong, please try again later</div>");
   timeOutAlert();
<% else %> 
   <!-- hidden the modals -->
   $('#myModal').modal('hide');
   $('#myModal .modal-title').html('');
   $('#myModal .modal-body').html('');

   <!-- Update The title of the accounts/_title from show.html.haml -->
   $('.page-header h1').html("<%= j render partial: 'title', locals:{account: @account} %>");

   <!-- Update the account block -->
   $('#account').html("<%= j render @account %>");

   <!-- Sending successfully alert -->
   $('#flash-alerts').html("<div class=\"alert alert-success\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\"><i class=\"ace-icon fa fa-times\"></i></button><i class=\"ace-icon fa fa-check green\"></i> Account was successfully updated.</div>");
   timeOutAlert();
<% end %>

到目前为止,我发现如果您在引导程序(版本 3)模式中插入表单,那么当您点击提交表单(远程:true)并且它成功时,ajax:success 回调将不会被触发。如果对象因为错误而回滚(属性不能为空),那么 ajax:success 它就是触发器。当我在 accounts/edit.html.haml 上使用表单时,我的 Jquery 验证被触发,并且 ajax:success 在对象更新时也被触发。谢谢你的帮助。

4

1 回答 1

1

也许这可能会有所帮助,根据文档,Rails 5.1作为依赖项引入rails-ujs和删除。jQuery因此,此引入导致在请求期间触发的自定义事件发生更改,请参阅:3.5 Rails-ujs 事件处理程序(边缘)

根据jquery-ujs wikiajax:error仅触发:

在服务器上处理请求失败时。
https://github.com/rails/jquery-ujs/wiki/ajax

这就是为什么ajax:success即使表单有验证错误,你也总是会得到。

于 2017-12-12T03:45:15.473 回答