目前,我有一个 View ,我将其渲染到模板并返回两个查询列表。我的看法如下图
def view_notifications(request,user_id):
context_instance=RequestContext(request)
user = User.objects.get(pk=user_id)
user.profile.notifications = 0
user.profile.save()
notices = list(notifications.objects.filter(n_reciever=user.id, is_read=0).order_by('-time'))
number = notifications.objects.filter(n_reciever=user.id, is_read=0).order_by('-time').count()
if number < 5:
old_notices = list(notifications.objects.filter(n_reciever=user.id, is_read=1).order_by('-time')[:5])
else:
old_notices = False
notifications.objects.all().update(is_read = 1)
return render_to_response('profiles/notifications.html', {'New_Notice': notices, 'Old_Notices':old_notices, 'number': number,},context_instance=RequestContext(request))
在我的模板中,我迭代两个列表,并为新的列表对象提供背景颜色
<ul id="notification_list">
<li id="first"></li>
{% for notice in New_Notice %}
<li class="new"> <a href="{{notice.n_sender.profile.get_absolute_url}}">{{ notice.n_sender.profile.url_name}} </a> {{notice.message}} your <a href="{{notice.object_url}}"> {{notice.object_type}}</a></li>
{% endfor %}
{% for notice in Old_Notices %}
<li> <a href="{{notice.n_sender.profile.get_absolute_url}}">{{ notice.n_sender.profile.url_name}} </a> {{notice.message}} your <a href="{{notice.object_url}}"> {{notice.object_type}}<a/></li>
{% endfor %}
</ul>
现在我想通过 AJAX
调用执行相同的操作,并在下拉列表而不是新页面中显示这些对象,以便用户可以在其中查看通知,而无需离开。我无法理解如何发送两个 JSON 编码的 object_lists
。我知道如何将对象列表序列化为 JSON
data = serializers.serialize('json', notifications.objects.all())
但是我可以通过这种方式发送两个object_lists吗?我也不知道如何在 html 中显示这个 JSON 编码的对象列表。我可以像访问模板中的对象一样访问它吗?
请帮忙
最佳答案
您想要发送一个包含两个元素的列表,每个元素对应一个列表。您可以通过首先序列化为 Python,然后将全部转储为 JSON 来完成此操作。
data1 = serializers.serialize('python', notifications.objects.all())
data2 = serializers.serialize('python', foobar.objects.all())
data = simplejson.dumps([data1, data2])
(或者您可以使用字典,如果在 JavaScript 中按键查找会更容易。)
关于django - 如何在 django 中的 AJAX 请求中返回多个 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8883129/