【问题标题】:Rails - Why jQuery Doesn't Load After Submitting My Form RemotelyRails - 为什么远程提交我的表单后 jQuery 不加载
【发布时间】:2013-05-16 07:37:13
【问题描述】:

为了简单起见,我有一个更新部分的表单。那里没什么特别的。在部分中,我有一个 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 重新加载?

【问题讨论】:

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


    【解决方案1】:

    原因是,您的自定义 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 将添加/更新的内容相关的部分即可。

    【讨论】:

    • 你刚刚改善了我的心情和我周围其他人的心情十倍:) 非常感谢。不是很简单!
    • @simonmorley,我很高兴能提供一点帮助 :)
    • @BillyChan 谢谢你,我只是在想——当我有一个循环,该部分被渲染一百次时,这意味着update.js.erb 中的代码也将被调用一百次- 这可能会减慢应用程序的速度。只是想知道 - 有没有更有效的解决方案?谢谢。
    • @user984621,我认为在你的情况下,上面的代码不能直接使用,需要一些修改。几点: 1. 我不认为渲染 100 次以上会让人觉得难看,特别是如果你有一个微调器出现。 2.如果真的需要,可以在服务器端编写整个html循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2011-11-24
    • 2012-10-07
    • 2012-02-28
    • 1970-01-01
    • 2012-05-26
    • 2013-04-26
    相关资源
    最近更新 更多