當我點擊喜歡按鈕時,我在控制臺中收到內部服務器錯誤。主要問題是從視圖函數(shù)返回HttpResponse。如何在HttpResponse中返回值,以便我可以在javascript中訪問?控制臺錯誤:jquery.js:9837 開機自檢 http://127.0.0.1:8000/blogs/post/like/ 500(內部服務器錯誤)視圖: class PostLikeView(generic.View): def post(self, request, *args, **kwargs): user = request.user post_id = request.POST['post_id'] post = Post.objects.get(id=post_id) user_liked, created = PostLike.objects.get_or_create(post=post, user=user) if not created: PostLike.objects.filter(post=post).filter(user=user).delete() total = post.like.count data = {'total-like':total,'user_liked':False} else : total = post.like.count data = {'total-like':total,'user_liked':True} return HttpResponse(json.dumps(data), content_type='application/json') javaScripts : <script type="text/javascript"> $('.likebutton').click(function(){ var id; id = $(this).attr("data-catid"); $.ajax( { type:"POST", url: "blogs/post/like/", data:{ csrfmiddlewaretoken: "{{ csrf_token }}", post_id: id }, dataType: 'json', }); //(function(data){ //data = JSON.parse(data) //console.log(data) // }); }); </script>
類型錯誤:方法類型的對象不可 JSON 序列化
萬千封印
2022-09-02 20:59:04