2014-01-10 59 views
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调用中做到这一点。

回答

0

保存不是activity_id,而是在用户浏览器中保存latest_activity日期。当查询ajax并且有新的活动时,在用户浏览器中保存最新活动的新日期,并在下一个ajax查询发送该日期,因此服务器端应用程序将在该日期之后仅发送活动。