【问题标题】:How to refresh a div without reloading the entire page?如何在不重新加载整个页面的情况下刷新 div?
【发布时间】:2016-09-04 01:23:49
【问题描述】:

我有一个div,我想在不重新加载整个页面的情况下刷新其内容。

我用很多方法(ajax 调用、javascript 等)尝试了很多次,但我没有这样做。

我的div显示ModelName.all的全部内容 在这个特定的 div 中,我们可以添加我使用的模型的新实体(感谢表单)。

感谢 Rails 部分视图,我显示了这个 div。

目前,我在用户提交表单时使用它:

$('#ArticlesDiv').html("<%= escape_javascript (render partial: 'articles') %>");

但我的部分观点似乎没有最新的模型。因为在我添加新实体之前,我看到了例如 5 个元素,而在我添加新实体之后,我又看到了 5 个元素。出于测试目的,我使用 javascript alert 显示 ModelName.all.count

警报显示5! 但是当我查看我的数据库内容时(在警报之前),我可以看到 6 个元素!当我手动刷新页面时,div 会显示 6 个元素。

解释代码:

主视图:

<div id="ArticlesDiv">
  <%= render(:partial => "articles") %>
</div>

_articles(部分视图):

<script>
  alert('<%=Article.all.count%>');
</script>

<% Article.all.each do |article|) %>

<strong><%= article.name %></strong><br />

<% end %>

我的目标是有一个流畅的界面,它不会在您添加其他文章时重新加载整个页面。

【问题讨论】:

  • $('#ArticlesDiv').html("&lt;%= escape_javascript (render partial: 'articles') %&gt;"); 你在哪里写的?

标签: javascript ruby-on-rails ajax refresh partial-views


【解决方案1】:

您可以将div 的内容放在部分中,然后使用URL (例如/divcontents)仅加载内容。您可以使用.load() 刷新&lt;div&gt;

$('#ArticlesDiv').load("/divcontents");

【讨论】:

    【解决方案2】:

    尝试使用jQuery的加载函数,你应该这样做:

    HTML:

    <div id="div1"></div>
    <button type="button" id="button">Test</button>
    

    jQuery:

    $(document).ready(function(){
        $("#button").click(function(){
            $("#div1").load("demo_test.txt");
        });
    });
    

    【讨论】:

      【解决方案3】:
      <script>
      $(document).ready(function () {
          // will call refreshPartial every 5 seconds
          setInterval(refreshPartial, 5000)
      
      });
      
      // calls action refreshing the partial
      function refreshPartial() {
        $.ajax({
          url: "page_url",
          dataType: 'script',
          format: 'js'
       })
      }
      </script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-07
        • 2011-11-02
        • 1970-01-01
        • 2022-08-19
        • 1970-01-01
        • 1970-01-01
        • 2020-11-14
        相关资源
        最近更新 更多