2015-05-06 37 views
1

在檢查了很多答案和教程以在rails中使用ajax之後,我走到了死衚衕。Ajax函數beforeSend和錯誤沒有被觸發

ajax:beforeSend和ajax:error不起作用,但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 %> 

回答

0

你應該這樣做這樣的:

  1. 請確保您有<%= csrf_meta_tag %>在佈局

  2. 添加beforeSend所有Ajax請求設置頭象下面這樣:


$.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

+0

你有沒有發現,爲什麼它不工作?我有和你一樣的代碼和beforeSend,錯誤也不起作用。 – Snake