Rails - 为什么远程提交表单后jQuery无法加载

时间:2013-05-21 13:46:17

标签: jquery ruby-on-rails-3 coffeescript ujs

为了简单起见,我有一个更新部分的表单。没什么特别的。在部分内容中,我有一个jQuery可排序列表。在更新表单之前,我可以毫无问题地拖动列表中的内容。

然而,在更新列表之后,就像js没有重新加载一样,我必须刷新整个页面才能让事情再次滚动。

我已经尝试了所有的东西,甚至借用了demo jQuery application from Ryan Bates Esq. over here.这在我将部分js shizzle放入部分之后也无效。

我确信它很简单,但我是一个ajax / jQuery新手,我真的很挣扎。

查看:

#test_one
  = render "test_one"

部分“test_one”

= form_for @location, :remote => true do |f|
  %table
    %tr= collection_select(:location, :type_ids, Type.all, :id, :name, {:prompt => true}, :multiple => true, :class=>"chzn-select")
     %tr
       %td
         %ul#types.unstyled{"data-update-url" => sort_types_locations_url}
           - @types.each do |type|
             = content_tag_for :li, type do
               %span.handle
                 [Drag]
               = type.name

update.js.erb

$("#test_one").html('<%= escape_javascript render("test_two") %>');

在我的控制器中:

  def update
    @location = Location.find(params[:id])
    @types = @location.types.order('location_types.position').limit(2)
    respond_to do |format|
      if @location.update_attributes!(params[:location])
        flash[:notice] = 'Settings updated successfully'
        format.html { redirect_to edit_location_path }
        format.js
      else
        format.html { render action: "edit_access" }
        format.js { render action: "update_access_errors" }
      end
    end
  end

最后在locations.js.coffee

jQuery ->
  $('#types').sortable(
      axis: 'y'
      update: ->
        $.post($(this).data('update-url'), $(this).sortable('serialize'))
      )

更新有效,我没有错误,我的控制台里什么都没有。现在我已经失去了很多 - 在更新记录后如何才能重新加载js?

1 个答案:

答案 0 :(得分:5)

原因是,您的自定义js(关于可排序)在文档就绪时加载,并且在部分更新后不会再次触发。

解决方案是:将自定义js包装到函数中。文档就绪和更新发生时调用此函数。

# locations.js.coffee
$ ->
  $(document).custom_js()

$.fn.custom_js ->
  $('#types').sortable(
    axis: 'y'
    update: ->
      $.post($(this).data('update-url'), $(this).sortable('serialize'))
    )

# update.js.erb
$("#test_one").html('<%= escape_javascript render("test_two") %>');
$(document).custom_js();

关于自定义js函数的附注:不需要在这里包装所有自定义代码,只需要与Ajax将要添加/更新的内容相关的部分。

相关问题