我有一个用户显示活动的源流,我必须在通过ajax调用加载页面后通知用户新活动。 以下是代码
views.py
@login_required
def new_activity(request):
context = {}
response = {}
latest_activity = []
prev_activity_id = request.GET.get('activity_id')
#get the latest activity from news feed
time_stamp = Activity.objects.get(pk = prev_activity_id).created
latest_activity = Activity.objects.filter(created__gt = time_stamp)
activity_count = latest_activity.count()
#Handle multiple activities
if activity_count == 1:
updated_id = latest_activity.id
elif activity_count > 1:
updated_id = latest_activity[0].id
else:
updated_id = prev_activity_id
context['activities'] = latest_activity
template = render_to_string('activities/new_activity_template.html', context, context_instance=RequestContext(request))
response['template'] = template
response['updated_id'] = updated_id
response['activity_count'] = activity_count
response['success'] = 'success'
return HttpResponse(simplejson.dumps(response), mimetype='application/json')
AJAX
(function new_activity() {
setTimeout(function() {
var activity_id = null
$.ajax({
url: "/activities/all/new_activity/?activity_id="+activity_id,
type: "GET",
success: function(response) {
$('#id_new_activity').empty();
$('#id_new_activity').append(response.template);
console.log(response.success);
//if activity_id is null get the activity id for first time
//if activity_id is not null update the activity_id from the response
activity_id = response.updated_id;
},
dataType: "json",
complete: new_activity,
timeout: 2000
})
}, 5000);
})();
如果在我的活动模型中创建了任何新对象,我需要在每次调用new_activity后更新最新的acitivity_id。此外,我还需要在加载页面时第一次传递activity_id。
我不知道如何在我的ajax调用中这样做。
答案 0 :(得分:0)
在用户浏览器中保存不是activity_id,而是保存latest_activity日期。当ajax查询并且有新活动时,在用户浏览器中保存最新活动的新日期,并且对于下一个ajax查询发送该日期,因此服务器端应用程序将仅在该日期之后发送活动。