Rails 5:ajax上的AJAX变量未定义:error / ajax:成功事件

时间:2017-06-13 11:33:43

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

我有一个form_with调用一个以JSON响应的控制器。我想在活动ajax:successajax:error期间运行javascript(处理错误,...)。

我遵循了Rails文档。不幸的是,我的活动中的变量是undefined。仅设置e

形式:

<%= form_with url: contact_path, scope: 'message', id: 'new_message' do |f| %>
    <div class="row">
      <div class="input-field col s6">
        <%= f.text_field :name, class: 'validate' %>
        <%= f.label :name, 'Nom' %>
      </div>
      <div class="input-field col s6">
        <%= f.email_field :email, class: 'validate' %>
        <%= f.label :email, 'Email' %>
      </div>
    </div>
    <div class="row">
      <div class="input-field col s6">
        <%= f.telephone_field :phone, class: 'validate' %>
        <%= f.label :phone, 'Téléphone' %>
      </div>
      <div class="input-field col s6">
        <%= f.text_field :website, class: 'validate' %>
        <%= f.label :website, 'Site Web' %>
      </div>
    </div>
    <div class="row">
      <div class="input-field col s12">
        <%= f.text_area :content, class: 'materialize-textarea validate' %>
        <%= f.label :content, 'Message' %>
      </div>
    </div>
    <div class="row">
      <div class="col s6">
        <%= recaptcha_tags %>
      </div>
      <div class="col s6">
        <%= button_tag class: 'btn primary waves-effect waves-light right' do %>
            Envoyer
            <i class="material-icons right">send</i>
        <% end %>
      </div>
    </div>
<% end %>

控制器:

def create
    @message = Message.new(message_params)

    respond_to do |format|
      if verify_recaptcha(model: @message) && @message.valid?
        MessageMailer.new_message(@message).deliver
        format.json { render json: @message, status: :created }
      else
        format.json { render json: @message.errors, status: :unprocessable_entity }
      end
    end
  end

CoffeeScript的:

$(document).ready ->
  $("#new_message").on("ajax:success", (e, data, status, xhr) ->
    console.log(xhr);
  ).on "ajax:error", (e, xhr, status, error) ->
    console.log(xhr);

结果:

undefined  message.self-5eda06948d26dade035273a7f168828c2cb1852e26937c49f50da7ca2532ad72.js:4:14


Started POST "/contact" for 127.0.0.1 at 2017-06-13 17:19:17 +0200
Processing by MessagesController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"aBxh+eJedXw0WifdUXFAlgH0gWxNpiDQa2J3hdJayC/wBaccIxNSVK4pycYwu9XMb1s2/r9S8+FteRFoocdrZQ==", "messages"=>{"name"=>"", "email"=>"", "phone"=>"", "website"=>"", "content"=>""}, "g-recaptcha-response"=>"03AOPBWq9SEfWUxzdyMRMdd0p65vonbGjNjA_mhCA07vfoXyA6_nEVn220Ot5HU90_KpQv6ziii0VCoa1hZosUcsARL7DuJbFHA2kt_NBHvnURmPpKR0SMq0OfulzJokvobdu9t1z33Uby3oTAtTgEAEmxX6yDc_yuwmqHXAjh5SL0bhAyD6AF2wAN8me7fMKMULu_DS5KtLgwJjK8B2TmvGydn0neHDWcfSbDKP7WRP-RQQePc9hDcOCbUFoVrW2kfpg3p4OV-hWiV4q6-HBRZK3A1mcj5rJZd_zBe3v-yx6LHAXB2Bsb9Uc", "button"=>""}
Completed 422 Unprocessable Entity in 2701ms (Views: 0.5ms | ActiveRecord: 856.3ms)

1 个答案:

答案 0 :(得分:5)

如果您使用的是rails-ujs适配器,请根据此Rails Edge Guide

  

对UJS事件处理程序的调用签名已更改。不像   使用jQuery的版本,所有自定义事件只返回一个参数:   事件。在此参数中,还有一个附加属性详细信息   其中包含一系列额外参数。

我建议您查看一下app/assets/javascripts/application.js并找出您当前使用的ujs适配器。 //= require rails-ujs是新的默认值。

查看指南中提供的示例。您可以通过以下方式提取datastatusxhr

document.body.addEventListener('ajax:success', function(event) {
  var detail = event.detail;
  var data = detail[0], status = detail[1],  xhr = detail[2];
})

另一种方法是使用jquery_ujs,它是Rails 5.1之前的默认值,并且具有更像您期望的签名。