31.收藏课程功能

2018-02-19  本文已影响0人  hs_a2d1
function add_fav(current_elem, fav_id, fav_type){
    $.ajax({
        cache: false,
        type: "POST",
        url:"/org/add_fav/",
        data:{'fav_id':fav_id, 'fav_type':fav_type},
        async: true,
        beforeSend:function(xhr, settings){
            xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
        },
        success: function(data) {
            if(data.status == 'fail'){
                if(data.msg == '用户未登录'){
                    window.location.href="/login/";
                }else{
                    alert(data.msg)
                }

            }else if(data.status == 'success'){
                current_elem.text(data.msg)
            }
        },
    });
}

$('.collectionbtn').on('click', function(){
    add_fav($(this),{{ course_org.id }}, 2);
});

if(data.msg == '用户未登录'){
window.location.href="/login/";
}else{
alert(data.msg)
}
如果data.msg == '用户未登录'则跳转window.location.href="/login/",否则alert(data.msg)
点击收藏按钮后,执行
$('.collectionbtn').on('click', function(){
add_fav($(this),{{ course_org.id }}, 2);
});这段在应用函数时候也会给fav_id, fav_type赋值{{ course_org.id }}, 2,传递给后台,后台

class AddFavView(View):
    """
    用户收藏,取消收藏
    """
    def post(self,request):
        fav_id = request.POST.get('fav_id',0)
        fav_type = request.POST.get('fav_type',0)

这样获取到fav_id, fav_type。

class AddFavView(View):
    """
    用户收藏,取消收藏
    """
    def post(self,request):
        fav_id = request.POST.get('fav_id',0)
        fav_type = request.POST.get('fav_type',0)

        if not request.user.is_authenticated():
            """
          判断用户登录状态
          """
            return HttpResponse('{"status":"fail","msg":"用户未登录"}',content_type='application/json')

        exist_records = UserFavorite.objects.filter(user=request.user,fav_id=int(fav_id),fav_type=int(fav_type))
        """
       fav_id和fav_type联合查询,如果只查一个fav_id,则fav_id=1时显示已收藏,fav_type=1也会显示已收藏
       """
        if exist_records:
            #如果记录已存在,则取消收藏
            exist_records.delete()
            return HttpResponse('{"status":"fail","msg":"收藏"}', content_type='application/json')
        else:
            user_fav = UserFavorite()
            if int(fav_id)>0 and int(fav_type)>0:
                user_fav.user = request.user
                user_fav.fav_id = int(fav_id)
                user_fav.fav_type = int(fav_type)
                user_fav.save()
                return HttpResponse('{"status":"success","msg":"已收藏"}', content_type='application/json')
            else:
                return HttpResponse('{"status":"fail","msg":"收藏出错"}',content_type='application/json')

后台处理完数据保存到operation里的userfavorite表里再返回给前端,前端就知道显示收藏还是已收藏。
还需要配置url,

url(r'^add_fav/$', AddFavView.as_view(), name="add_fav"),

但是这个地址还打不开,只是在ajax里add_fav函数的url里用了下,不知道为啥。

上一篇下一篇

猜你喜欢

热点阅读