我正在构建一个聊天应用程序。到目前为止,我正在使用 jquery $.post() 添加聊天消息,这工作正常。
现在我需要从表中检索最新的聊天消息并将列表附加到聊天页面上。 我是 Django 的新手,所以请慢慢来。
那么如何从聊天表中获取数据返回到聊天页面呢?
提前致谢!
最佳答案
我最喜欢的技术是使用 inclusion tag
基本上,您制作了一个单独的模板来呈现页面模板中的各个对象
页面模板:
{% load message_tags %}
<h3>Messages</h3>
<div class="message_list">
{% for message in messages %}
{% render_message message %}
{% endfor %}
</div>
templatetags/message_tags.py:
from django import template
register = template.Library()
@register.inclusion_tag('individual_message.html')
def render_message(message):
context_for_rendering_inclusion_tag = {'message': message}
return context_for_rendering_inclusion_tag
现在您可以使用相同的模板在单独的 View 中呈现您想要添加到 message_list
div 的其他消息,您可以从您的 ajax 代码中调用该 View
def ajax_retrieve_latest_message(request):
# ... Get the lastest message
render_to_response('individual_message.html', ...
你的 jQuery 看起来像...
$.post(url_of_ajax_view, request_data, function(data, status) {
if (status == 'success') {
$(".message_list").append(data);
}
});
为了完整起见,您的 individual_message.html
文件将包含用于在页面上显示实际消息的所有标记...
希望这一切对您有所帮助:)
关于jquery - Django : Update div with AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1879872/