【问题标题】:Problem in replacing body contents with ajax from a django HttpResponse用 django HttpResponse 中的 ajax 替换正文内容的问题
【发布时间】:2019-04-04 13:46:57
【问题描述】:

我正在使用 Django 作为服务器并尝试使用 ajax 定期更新正文标记中的内容。 ajax 部分如下所示:

<html>
<head>
<meta charset="utf-8">
<title>A Pyecharts Demo</title>
{% for jsfile_name in script_list %}
    <script src="{{ host }}/{{ jsfile_name }}.js"></script>
{% endfor %}
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>

<script>
setInterval(function() {
$.ajax({
     url:"/first_pyecharts/",
     type:'POST',
     data:{ 'last_update':'{{ last_update }}', 'csrfmiddlewaretoken': '{{ csrf_token }}' },
     dataType: "html",
     success: function (html) {
        document.getElementById("body").innerHTML = html
    }
});
}, 10000);
</script>

<body id="body"> 
<!-- contents to be replaced -->
</body>

views.py中的相关代码:

if last_update is None:
    update_context(cur)
    template = loader.get_template('pyecharts.html')
    return HttpResponse(template.render(context, request))
elif latest > datetime.strptime(last_update, '%Y-%m-%d %H:%M:%S'):
    update_context(cur)
    template = loader.get_template('pyecharts.body.html')
    return HttpResponse(template.render(context, request))
else:
    template = loader.get_template('pyecharts.body.html')
    return HttpResponse(template.render(context, request))

服务器返回一个带有模板的 HttpResponse,该模板由先前存储的或基于从 ajax 提交的“last_update”的新上下文呈现。

这里的模板“pyecharts.html”是一个完整的页面,上面有“html”、“head”、“script”和“body”部分。而'pyecharts.body.html'只包含'body'部分的内容,用于更新网页内部的'body'标签。

但是当 ajax 从 Django 获取响应时,它似乎已经用响应替换了整个页面,删除了网页的其余标签。

谁能告诉我我哪里做错了?是因为模板同时呈现了上下文和请求吗?因为我只从 Django 文档中找到了带有上下文的渲染方法。我不确定。

【问题讨论】:

  • 脚本不是页面的独立部分,不能独立存在。它需要在头部或身体内部。
  • @DanielRoseman 感谢您的建议,我将脚本部分移到了头部。但我认为脚本确实有效,尽管它是单独放置的。因为它确实每 10 秒发送一次 POST 请求。现在我怀疑响应中的 javascripts 没有正确执行,因为响应几乎是由 pyecharts 生成的 javascripts 形成的。

标签: jquery ajax django


【解决方案1】:

最好将动态内容保留在部分模板中。 创建一个部分 html 文件并将动态内容保留在那里。

使用render_to_string(),像这样将数据发送到模板

from django.template.loader import render_to_string

def get_item(request):
    # your code
    if last_update is None:
        html = render_to_string('your_path_to_the_partial', {'context_variable': variable})
        return HttpResponse(html)
    .....

现在接收模板中的数据并将其放入 #dynamic_content 中,就像您之前使用 js 所做的一样。

<body>
    <div id="dynamic_content"></div>
</body>    

【讨论】:

  • 谢谢。这就是我想要做的。 'pyecharts.body.html' 对应于您在此处提到的部分部分。响应中的 javascript 是否有可能未正确执行?这里的响应主要是由pyecharts生成的javascripts形成的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
相关资源
最近更新 更多