2013-05-17 56 views
0

因此,我有以下表單部分允許用戶向表中添加值。我對使用Ajax和JavaScript非常新,所以我不完全確定如何去做這件事。但是,一旦輸入值並提交,我希望能夠顯示已輸入的值。目前,我必須重新加載頁面才能發生。我有一個html部分和移動部分用於jQuery的移動。如何將這些表單更改爲ajax表單rails

#_form.html.erb 

<% if @workoutexercises[n].exercise_weight.nil? %> 
    <%= form_for @workoutexercises[n], :remote => true do |f| %> 
    <div class="input-append"><%= f.text_field :exercise_weight, :class => 'submittable input-small' %> 
    <%= button_tag(type: 'submit', class: "btn btn-primary", disable_with: 'Processing...') do %> 
     <i class="icon-ok icon-white"></i> 
    <% end %></div> 
    <% end %> 
<% else %> 
    <%= @workoutexercises[n].exercise_weight %> 
<% end %> 

#_form.mobile.erb 

<% if @workoutexercises[n].exercise_weight.nil? %> 
    <%= form_for @workoutexercises[n], :remote => true do |f| %> 
    <%= f.label :exercise_weight %> 
    <div class="ui-grid-a"> 
     <div class="ui-block-a"><%= f.text_field :exercise_weight, :class => 'submittable' %></div> 
     <div class="ui-block-b"><%= f.submit "Update", "data-role" => "button", "data-theme" => "b" %></div> 
    </div> 
    <% end %> 
<% else %> 
    </n> 
    Weight: <%= @workoutexercises[n].exercise_weight %> 
<% end %> 

我正在使用以下提交的javascript。

#application.js 

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

在預先感謝任何提示或正確的方向導致!乾杯

回答

0

在您workoutexercises控制器適當的行動,在你的respond_to塊添加一個新的生產線,以允許JavaScript的響應,如下所示:

respond_to do |format| 
    format.html { redirect_to workoutexercises_url } 
    format.js // add this line here 
end 

然後創建一個新的JS視圖模板,打了個比方「 update.js.erb「(如果表單提交給更新操作)。還可以在同一個目錄中創建一個新的部分,您可以調用_show.html.erb。

在update.js.erb文件,你會希望有這樣的事情:

// Render the newly created workout into your table 
$('#someTableCell').html("<%= j render ("show") %>"); 

,這會使得部分(_show.html.erb)包含您最近更新的演習到表上你的頁面通過ajax。

如果您使用不顯眼的javascript(即在表單頭中使用remote => true),那麼您不需要在問題結束時使用JavaScript。

+0

感謝您的回覆,它爲如何使用Unobtrusive Javascript提供了很多清晰的內容。不過,我現在正在遇到另外兩個問題。第一個是我收到這個錯誤:'ActionView :: Template :: Error(部分名稱()不是一個有效的Ruby標識符;確保您的部分名稱以字母或下劃線開頭,後面跟着任何組合字母,數字或下劃線。)' – Sean

+0

請參閱上面的編輯。 j是escape_javascript方法的簡寫(我最初在渲染之後把它放在了錯誤的位置)。另外,爲了讓你的更新中傳遞錯誤的id,我會查看嵌套的模型表單。請參閱Ryan Bates關於此處的截屏:http://railscasts.com/episodes/196-nested-model-form-revised?view=comments。 – kwyoung11

+0

您可能在更新操作中使用了錯誤的路徑助手重定向。在終端中運行耙路徑以獲取可用路徑。它可能應該是workout_workoutexercises路徑和形式訓練/:id/workoutexercises /:id。 – kwyoung11

相關問題