0
我有一个在其中显示用户活动的源流,我必须在通过ajax调用加载页面之后通知用户新活动。 下面是代码在django中通过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调用中做到这一点。