2012-01-06 18 views
0

我用.submit()方法發送數據。jQuery與Rails - 沒有做功能裏面提交

我有一個問題形式的替代品,當我點擊一個鏈接後,會自動使用這個對數據庫更新:

的application.js

function save_response_with_ajax(t){ 
    $('#edit_response_set_' + t).submit(); 
    } 

和單選按鈕是這樣的:

<%= rs_a_form.input :answer_id, 
      :collection => "code that gets the info", 
      :as => :radio, 
      :input_html => { 
    :onclick => 'save_response_with_ajax(' + response_set.id.to_s + ');'} %> 

一切工作正常,但是當我點擊了很多倍單選按鈕,形式再次呈現,所以我一直在尋找如何避免多個Ajax請求(唯一即使我點擊很多次),我必須使用$ .ajax()方法。 問題是我寫的時候:

function save_response_with_ajax(t){ 
    $("#form").submit(function(){ 
     //it suppose to be $.ajax(url, .....) instead of alert 
     // I'm just testing 
     alert("hi"); 
    }); 
} 

什麼也沒有發生。

希望有人能幫助我

+0

首先,你應該使用遠程形式 - 它很容易而且你不必編寫自己的JS。但在我看來,在這種情況下,您的問題是在單擊事件中嵌套提交事件。在save_response_with_ajax方法中,你應該做2件事情,先禁用按鈕,然後用ajax做一些事情。 – codevoice 2012-01-06 19:19:59

+0

是的我使用遠程,主要問題是我可以做出多次ajax調用,如果點擊很多次(這是一種錯誤,因爲如果他們點擊很多,它會再次渲染很多形式) – JavierQQ23 2012-01-06 19:48:48

+0

那麼第一次點擊後有什麼問題的禁用按鈕?添加到您的提交按鈕選項:disable_with =>「正在提交...」 – codevoice 2012-01-07 10:12:00

回答

0

爲了避免多次提交,你可以使用global ajax event handlers觸發功能,當AJAX請求開始和結束等

$(document).ajaxStart(function(){ 
    //add js to disable your inputs so you can not trigger the submit again. 
    }) 
    .ajaxStop(function(){ 
    //add js to re-enable your inputs that you disabled in ajaxStart 
    }) 
    .ajaxError(function(){ 
    //add js here to alert user that a problem occurred. 
    });