【问题标题】:rendering rails partial in a js.erb without reloading the entire page在 js.erb 中渲染 Rails 部分而不重新加载整个页面
【发布时间】:2018-03-09 16:33:18
【问题描述】:

我的页面中有一个部分在我加载页面时被加载。部分在加载时被这样调用。

<%= f.simple_fields_for :application_attachments do |attachment| %>
        <%= render "attachment_fields", {:f => attachment, :instalment => true, :type => 'application_assignment'} %>
      <% end %>

然后我运行一些函数来更改 application_attachments 关联的值,我只需要重新加载该部分并呈现最新信息。

我更新值的方法有一个 js.erb 文件,我尝试像这样更新和渲染部分

generate_attachment.js.erb

    <% form_for @application do |f| %>
        <%= f.fields_for :application_attachments do |attachment| %>
            $("<%= escape_javascript render(partial: 'attachment_fields', locals: {f: attachment}, :instalment => true, :type => 'application_assignment') %>")
                .appendTo($("#application-attachments-#{@rand_value}"));
        <% end %>
    <% end %>

基本上我只是想重新渲染渲染部分的部分并更新值,但它不起作用。

我不确定还能做什么或如何使用最新的 html 部分更新所需的 div。任何建议或选择表示赞赏

【问题讨论】:

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


    【解决方案1】:

    试试这个:

    1- 为此制作部分内容:(_custom_partial.html.erb)

    <%= f.simple_fields_for :fields_for_param do |attachment| %>
      <%= render "attachment_fields", {:f => attachment, :instalment =>
     true, :type => 'application_assignment'} %> 
    <% end %>
    

    2-页面结构应该是这样的:

    <% form_for @application do |f| %>
     <div id="my_id">
      <%= render partial: 'custom_partial', locals: {fields_for_param: 
       application_attachments}%>
     </div>
    <% end %>
    

    3- 在 js.erb 文件中仅重新加载 my_id div 具有可变内容,如

    $('#my_id').html('<%= j render 'custom_partial', locals: {fields_for_param: your_changebale_variable}%>');
    

    您可以根据自己的需要修改此代码。希望这会奏效。谢谢。

    【讨论】:

    • 这个实现@anand 的一个大问题是简单的字段对象 f 呢?对于 js erb 和页面结构,我从哪里传递 f?
    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    相关资源
    最近更新 更多