将部分视图注入div标签

时间:2015-10-26 13:03:41

标签: javascript jquery html ruby-on-rails ruby-on-rails-4

我有一种情况,我想根据按钮点击动态更改一个div标签的内容。对于每个按钮单击我想注入一些html.erb部分。

为什么这样的事情不起作用:

$('#my_div').append '<%= escape_javascript(render("shared/my_partial")) %>'

我的部分内容采用以下格式:_my_partial.html.erb

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

好的,这里有几个问题:

  1. 您是否未将div替换件绑定到活动?
  2. 您在ERB javascript中使用front-end代码(仅适用于ajax来电)
  3.   

    对于每个按钮单击我想注入一些html.erb部分

    这里有两个选项可以通过ajax调用部分(只有在你有动态部分的情况下才推荐)或者在helper方法中预加载部分...

    我将详细介绍这两种方法。

    -

    <强>的Ajax

    如果您的部分内容具有动态内容(IE中填充了变量或类似内容),则您需要通过Ajax传递请求。

    原因是Ruby可以处理服务器上的<%= ERB %>代码。由于Javascript是客户端的,因此您必须使用ajax将异步请求传递给您的服务器,这将为您呈现JS。

    Rails UJS引入了remote标记 - 这消除了此过程中的许多麻烦:

    #app/view/controller/your_current_view.html.erb
    <%= link_to "your post", your_current_view_path, remote: true %>
    
    #app/controllers/controller.rb
    class Controller < ApplicationController
       respond_to :js, :html #-> will need the responders gem after Rails 4
    
       def your_current_view_path
          ....
       end
    end
    

    这将允许您使用服务器中的以下js.erb文件:

    #app/views/controller/your_current_view.js.erb
    $('#my_div').append('<%=j render "shared/my_partial" %>');
    

    这将允许您使用您在操作中设置的部分@instance_variables

    -

    独立JS

    如果您的partial是&#34;静态&#34; (不需要任何动态数据),您将能够使用以下内容:

    #app/views/controller/your_current_view.html.erb
    <%= content_tag :div, class: "hidden" do %>
       <%= render "shared/my_partial" %>
    <% end %>
    

    这将允许您使用以下JS:

    #app/assets/javascripts/application.js
    $("a.link").on("click", function(e){
       e.preventDefault();
       hidden = $(".hidden").html();
       $("div").html(hidden);
    });