【问题标题】:Rails form not submitting on change with ajaxRails 表单未通过 ajax 提交更改
【发布时间】:2014-11-29 02:01:22
【问题描述】:

我正在开发一个带有 ruby​​ on rails 的小待办事项列表应用程序,我想在选中复选框时通过 ajax 提交表单。我一直在关注this guide 尝试这样做。

虽然更改复选框并没有提交表单,所以我在 SO 上搜索了类似的问题并对我的代码进行了一些更新。

  1. 使用on() instead of live()
  2. 提交closest form instead of form.first,因为我在同一页面上有这些表单的列表

它仍然不会提交。我感觉它没有正确观看“.submittable”,因为我什至无法在单击复选框时收到闪烁的警报。

有什么建议吗?我忘记了什么吗?谢谢。

index.html.erb

<table class="table table-striped">
  <tr>
    <th>Task Description</th>
    <th width="15%">Days Left</th>
    <th width="15%">Completed?</th>
  </tr>
  <% @tasks.each do |task| %>
  <tr>
    <td><%= task.description %></td>
    <td><%= task.days_remaining %> days left</td>
    <td><%= form_for task, remote: true  do |f| %>
        <%= f.check_box 'completed', id: "task-#{task.id}", class: 'submittable' %>
    <% end %>
        </td>
  </tr>
  <% end %>
</table>

application.js

$('.submittable').on('change', function() {
  $(this).closest('form').submit();
});

update.js.erb

<% if @task.updated? %>
   $('#task-' +<%= @task.id %>).prepend("Yes");
<% else %>
   $('#task-' +<%= @task.id %>).prepend("<div class='alert alert-error'><%= flash[:error] %></div>");
<% end %>

【问题讨论】:

    标签: javascript jquery ruby-on-rails ruby ajax


    【解决方案1】:

    您的代码似乎没有包含在对$(document).ready() 的调用中,因此 jQuery 可能试图在您的复选框加载之前绑定事件。试试这个:

    $(document).ready(function () {
      $('.submittable').on('change', function() {
        $(this).closest('form').submit();
      });
    });
    

    【讨论】:

    • 啊,我真的忘记了一些重要的事情。谢谢!
    • 不用担心,很高兴为您提供帮助。
    【解决方案2】:

    你必须等到 dom 加载完毕

    $(function(){
     $('.submittable').on('change', function() {
       $(this).closest('form').submit();
     });
    });
    

    然后确保在您的控制器更新操作中

    respond_to do |format|
      if @object.update(object_params)
        .
        .
        format.js
      else
       .
       .
      end
    end
    

    看到这个 episode 的 railscasts 他正在解释你想做什么

    【讨论】:

    • 亲爱的,我去看看这一集
    猜你喜欢
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    相关资源
    最近更新 更多