如何将这些表单更改为ajax表单rails



所以我有以下表单部分,允许用户向表添加值。我很新的工作与ajax和javascript,所以我不完全确定如何去做这个。但是,一旦输入并提交了值,我希望能够显示已输入的值。目前,我必须重新加载页面才能实现这一点。我有一个html部分和一个移动部分与jquery移动使用。

#_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();
});

提前感谢任何提示或引导正确的方向!欢呼声

在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. erbb。

在update.js.erb文件中,您将需要这样的内容:

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

这将通过ajax将包含新更新练习的部分(_show.html.erb)呈现到页面上的表中。

没有必要的javascript你有在你的问题结束,如果你使用不显眼的javascript(即使用remote => true在你的表单头)。

最新更新