javascript - 更新网页的一部分而不刷新

标签 javascript jquery html ajax django

我正在使用 Django 实现一个网站。我在网上搜索了有关更新网页的一部分而不刷新整个页面的信息,但这些对我不起作用,可能是因为我想要更新的部分(div)实际上是由javascript实现的(使用脚本包含在html中)。我唯一更新的是脚本中的变量,这个结果应该反射(reflect)在网站上。这是我在 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'),

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

非常感谢!

最佳答案

您需要从 html show_result.html 中删除 id="result" 因为一旦您第一次加载它,您的 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

关于javascript - 更新网页的一部分而不刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38579453/

相关文章:

php - CSS 不是从本地主机呈现的 - 但仅在 Chrome 和 IE 中呈现

javascript - 在 Highcharts 'stacked & grouped column' 布局中显示整个组的总计

javascript - 使用 dojo 淡入/淡出文本和循环

在不使用 array.map() 的情况下添加任意数量的数组值的 Javascript 矩阵

每个文本框的 JavaScript 取决于下拉列表

html - 动态大小的 html 视频,其正下方有元素

html - 将 <select size ="10"> 转换为 Safari 移动版 (iOS) 上的可用列表的 jquery 插件

Javascript 过滤功能无法正常工作

jquery - 如何改变选择框的宽度

javascript - 如何以交互方式切换网页上的 CSS 工作表以进行测试/学习?