(二十三)小程序详细页赞的处理
后端api
url(r'^favor/', news.FavorView.as_view()), class FavorModelSerializer(serializers.ModelSerializer): class Meta: model = models.NewsFavorRecord fields = ['news'] class FavorView(APIView): authentication_classes = [UserAuthentication, ] def post(self, request, *args, **kwargs): ser = FavorModelSerializer(data=request.data) if not ser.is_valid(): return Response({}, status=status.HTTP_400_BAD_REQUEST) news_obj = ser.validated_data.get('news') queryset = models.NewsFavorRecord.objects.filter(user=request.user, news=news_obj) exists = queryset.exists() if exists: queryset.delete() return Response({}, status=status.HTTP_200_OK) models.NewsFavorRecord.objects.create(user=request.user, news=news_obj) return Response({}, status=status.HTTP_201_CREATED)
小程序端
<text wx:if="{{news.is_favor}}" class="red" bindtap="doFavor" data-news="{{news.id}}">赞</text> <text wx:else bindtap="doFavor" data-news="{{news.id}}">赞</text>
// js doFavor:function(e){ if(!app.globalData.userinfo){ wx.navigateTo({ url: '/pages/auth/auth', }) return } var news_id = e.currentTarget.dataset.news wx.request({ url: api.FavorAPI, data: { news:news_id }, header: { 'Authorization': app.globalData.userinfo ? app.globalData.userinfo.token : null }, method: 'POST', dataType: 'json', responseType: 'text', success: (res)=> { console.log(res) if(res.statusCode==200){ this.setData({ ['news.is_favor']:false }) }else if(res.statusCode==201){ this.setData({ ['news.is_favor']: true }) }else{ wx.showToast({ title: '请求错误', icon:'none' }) } }, }) },