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調用中做到這一點。