2012-03-13 41 views
0

在我的Rails 3.1應用程序中,我有一個Jquery對話框,點擊時彈出,並且裏面有一個提交按鈕。我做了一些嘗試,使這個'提交'按鈕阿賈克斯。所以當它被點擊時它會更新預約時間和日期。我有以下代碼:單擊提交按鈕時觸發Ajax調用

<% if @booking.id and current_user.is_booking_manager? %> 
<button id="confirm_appointment"> 
    test confirmation 
</button> 
<div style="display:none;"> 
    <div id="confirm_appointment_dialog" title="Test Confirm Booking"> 
     <%= form_for @booking, :url => booking_confirmation_path(@booking), :remote => true do |f| %> 
     <%= f.hidden_field :id %> 
     <%= f.datetime_select :confirmed_appointment %> 
     <br /> 
     <b>Clear provisional appointment:</b><%= check_box_tag "make_unexpected" %> 
     <br /> 
     <%= f.submit :class => 'submit_me' %> 
     <% end %> 
    </div> 
</div> 
<% end %> 

的application.js

$('.submit_me').bind('change', 
function() { 
    $(this).parents('form:first').submit(); 
}); 

有我丟失的東西

+0

重新加載頁面後會更新嗎?在這種情況下,您需要定義一個create.js.erb或一個update.js.erb並在那裏更新頁面。 此外,據我所知,綁定代碼並不是必需的,因爲:在您的表單實例化中:remote => true已經使表單「ajax」已經 – 2012-03-13 11:35:53

+0

是的,它在頁面重新加載後更新 – David 2012-03-13 11:36:38

+0

所以你說我應該創建一個update.js.erb並把我的JavaScript裏面? – David 2012-03-13 11:37:01

回答

1

在處理JS請求後,您不會更新您的視圖。首先,您需要爲要更新的HTML元素添加一個ID。

你Pastie過這樣的代碼:

<tr> 
    <td><%= f.label :confirmed_appointment %></td> 
    <td> <% f.hidden_field :confirmed_appointment %> 
    <% if @booking.confirmed_appointment %> 
    <%= l @booking.confirmed_appointment %> 
    <% else %> <em>unconfirmed</em> <% end %> </td> 
</tr> 

爲了可以很容易地引用您想在JavaScript中更新的一部分,讓我們的ID添加到TD。

<td id="booking-confirmation"> <% f.hidden_field :confirmed_appointment %> 

之後,你需要在你的views /文件夾中創建一個update.js.erb。現在,你可以把線

$("#booking-confirmation").html("<%= l @booking.confirmed_appointment %>"); 

在那裏,這將尋找與你的HTML ID爲「預訂,確認」字段和更新。

最後,一定要包括

respond_to do |format| 
    format.html 
    format.js 
end 

在你的行動,讓行動來響應JS調用。