我使用Django作为服务器,并尝试使用ajax定期更新body标记中的内容。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得到响应时,它似乎已经用响应替换了整个页面,删除了网页的rest标记。
有没有人能告诉我我哪里做错了?是不是因为模板同时使用上下文和请求呈现?因为我只在Django文档中找到了带有上下文的render方法。我没有把握。
发布于 2018-10-31 21:17:29
最好将动态内容保存在部分模板中。创建一个局部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> https://stackoverflow.com/questions/53082590
复制相似问题