Ajax函数beforeSend并且未触发错误

时间:2015-05-06 20:03:07

标签: jquery ruby-on-rails ajax

在检查了许多答案和教程以便在轨道中使用ajax之后,我走到了死胡同。

ajax:beforeSend和ajax:错误无法正常工作,但是当我第一次加载页面时,ajax:success工作正常。

我无法找到一种方法来完成这项工作,但自从我开始尝试以来,我做了很多改变。我在stackoverflow中发现了很多类似的问题,但是它们都有不同的方法。

提交表单后,成功响应出现,其他ajax功能正常工作。我的意思是,我从rails中松开了客户端验证,并且表单可以在没有任何内容的情况下提交,有beforeSend和错误工作。

无论如何,如果你们能给我一些关于它的错误的信息,我会很感激。

controller.rb

def create
  @message = Home.new(message_params)

  respond_to do |format|
    if @message.valid?
      ContactMailer.new_message(@message).deliver_now
      format.html { redirect_to root_path, notice: "Mensagem enviada com sucesso" }
      format.js
    else
      format.html { redirect_to root_path, alert: "Houve um erro ao processar sua mensagem. Por favor, tente novamente." }
      format.js { render json: @message.errors.full_messages, status: :unprocessable_entity }
    end
  end        
end

create.js.erb

$('#new_home')
  .on("ajax:beforeSend", function(evt, xhr, settings){
  alert("beforeSend worked");
})
  .on("ajax:success", function(evt, data, status, xhr){
    $( "#form_int" ).append("<p>Mensagem enviada com sucesso.<br>Obrigado pelo contato.</p>");
    $(this)[0].reset();
})
  .on("ajax:error", function(evt, xhr, status, error){
    alert("error worked");
});

form.html.erb

<%= form_for @message, remote: true, validate: true, url: root_path do |f| %>
  <fieldset>
    <div class="fields">
      <%= f.text_field :name, placeholder: "Nome Completo", class: "name" %>
    </div>
    <div class="fields">
      <%= f.email_field :email, placeholder: "E-mail", class: "email" %>
    </div>
    <div class="fields">
      <%= f.text_field :phone, placeholder: "Telefone com DDD", class: "phone" %>
    </div>
    <div class="fields">
      <%= f.text_field :city, placeholder: "Cidade", class: "city" %>
    </div>
    <div class="fields">
      <%= f.text_field :state, placeholder: "Estado", maxlength: 2, class: "state" %>
    </div>
    <div class="fields message_content">
      <%= f.text_area :content, placeholder: "Mensagem", class: "content" %>
    </div>
  </fieldset>
  <fieldset id="form_int">
      <%= f.submit "Enviar", class:"send_form" %>
  </fieldset>
<% end %>

1 个答案:

答案 0 :(得分:0)

你应该这样做:

  1. 确保您的布局中有<%= csrf_meta_tag %>

  2. beforeSend添加到所有ajax请求中以设置标题,如下所示:

  3. $.ajax({ url: 'YOUR URL HERE',
      type: 'POST',
      beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
      data: 'someData=' + someData,
      success: function(response) {
        $('#someDiv').html(response);
      }
    });
    

    要在您可以使用的所有请求中发送令牌:

    $.ajaxSetup({
      headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
      }
    });
    

    来源:https://stackoverflow.com/a/8175979/657509