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

时间:2016-07-26 00:42:22

标签: javascript jquery html ajax django

我正在使用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(r'^display_list/$', views.display_list, name='display_list'),

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

非常感谢!

2 个答案:

答案 0 :(得分:0)

您需要从html id="result"中删除show_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

答案 1 :(得分:0)

我认为问题在于你的main.html中没有id =&#34;结果&#34;的div。 你需要把它放,因为下面的js会寻找它。

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

所以只需将它放在main.html

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

另一种方法是编辑此

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

到这个

$('#display_list').html(ret);
相关问题