【问题标题】:Updating a section of the webpage without refreshing在不刷新的情况下更新网页的一部分
【发布时间】:2016-11-29 11:40:18
【问题描述】:

我正在使用 Django 实现一个网站。我在网上搜索了关于在不刷新整个页面的情况下更新网页的一部分,但这些对我不起作用,可能是因为我要更新的部分(div)实际上是由 javascript 实现的(使用脚本包含在 html 中)。我唯一更新的是脚本中的一个变量,这个结果应该反映在网站上。这是我在 main.html 中的代码

# I first have a button that could be clicked
<div class="col-lg-4">
     <p><button class="btn btn-primary" type="button" name="display_list" id="display_list">Display List</button></p>
</div>
# here is the script I include to update the section without refreshing the whole page
<script>
        $(document).ready(function(){
          $("#display_list").click(function(){
            $.get("display_list/", function(ret){
                $('#result').html(ret);
             });
          });
        });
</script>

我在一个单独的 html 文件 (show_result.html) 中有要更新的部分的代码:

<div id="result">
<script> javascript that draws a graph on html webpage. I pass the updated variable from the corresponding function in views.py to here by calling render(). </script>
</div>

这是我在views.py中的函数:

def display_list(request):
    #some function implementation to get the result and put it in context
    return render(request, "show_result.html",context)

这是我的 url 文件中的代码:

url(r'^display_list/$', views.display_list, name='display_list'),

如果需要,我可以提供更多信息。但我不明白为什么每当我单击按钮时,图表都会附加到原始网页而不是在同一个地方更新它。我该如何修改以刷新该部分而不是附加到原始页面?

非常感谢!

【问题讨论】:

    标签: javascript jquery html ajax django


    【解决方案1】:

    你需要从你的 html 中删除 id="result" show_result.html 因为一旦你第一次加载它,你的 html 就会像这样

    <div id="result">
      <div id="result">
         <script> javascript that draws a graph on html webpage. I pass the updated variable from the corresponding function in views.py to here by calling render(). </script>
      </div>
    </div>
    

    多个项目具有相同的id 是无效的html

    【讨论】:

    • 对不起,我不明白为什么会有两个&lt;div id="result"&gt;?我只在 html 文件的开头定义了一次。如果我只是说&lt;div&gt;,那么main.html($('#result').html(ret);) 中的这行代码如何工作?
    • 我尝试并做了&lt;div&gt;。但是当我单击按钮时,图形的那部分并没有自行刷新。只有当我刷新整个页面时才会刷新。
    【解决方案2】:

    我认为问题在于您的 main.html 中没有 id="result" 的 div。 需要放,因为下面的js会找它。

    $('#result').html(ret);
    

    所以把它放在 main.html 中

    <div id="result"></div>
    

    另一种方法是编辑它

    $('#result').html(ret);
    

    到这里

    $('#display_list').html(ret);
    

    【讨论】:

    • 我尝试了这两个,但它们仍然附加到原始页面而不是更新页面。我不明白他们为什么要追加而不是更新页面的该部分。
    • 它只会更新结果 div 而不是整个页面。这就是 ajax 的用途。
    猜你喜欢
    • 2012-09-23
    • 1970-01-01
    • 2017-03-24
    • 2021-12-22
    • 2021-02-05
    • 2017-08-13
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    相关资源
    最近更新 更多