不知道要为Django中的Ajax返回什么数据?

时间:2019-06-25 12:45:06

标签: javascript python django ajax

我想使用JavaScript使我的Like按钮异步,就像可以发布帖子一样,一旦我刷新页面,喜欢计数就会增加,但是我希望喜欢计数增加而不刷新。我试图在不使用任何框架的情况下使用纯JavaScript做到这一点,以便让我知道它是如何真正知道其工作原理的。有人可以解释如果request.is_ajax()为True,应该返回什么。

class PostModel(models.Model):
    user = models.ForeignKey(User, default=1, on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    message = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    likes = models.ManyToManyField(User, blank=True, related_name='post_likes')


    def __str__(self):
        return self.title

    objects = PostManager() 

    def get_absolute_url(self):
        return reverse("birdpost:detail", kwargs={"id": self.id})

    def get_like_url(self):
        return reverse("birdpost:like-toggle", kwargs={"id": self.id})  
class PostLikeToggle(RedirectView):

    def get_redirect_url(self, *args, **kwargs):
        id_ = self.kwargs.get("id")
        request = self.request
        obj = get_object_or_404(PostModel, id=id_)
        url_ = obj.get_absolute_url()
        user = self.request.user
        liked = False
        updated = False

        if user.is_authenticated:
            if user in obj.likes.all():
                obj.likes.remove(user)
                liked = False
            else:
                obj.likes.add(user)
                liked = True
            updated = True      

            data = {
                "liked": liked,
                "updated": updated
            }       

            if request.is_ajax:
                print("AJAX Call.")

            return url_
var likeButton = document.getElementsByClassName("like-btn");
for (var i = 0; i < likeButton.length; i++){
        likeButton[i].addEventListener('click', function(event){
            event.preventDefault()
            var likeEndPoint = this.getAttribute("href");

            if (window.XMLHttpRequest) {
                xhttp = new XMLHttpRequest();
            } else {
                xhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }

            xhttp.onreadystatechange = someCallBack;

            function someCallBack() {
                if(xhttp.readyState < 4){
                    return;
                }
                if( xhttp.status != 200 ){
                    return;
                }
            }
            xhttp.open('GET', likeEndPoint, true);
            xhttp.send();

});

1 个答案:

答案 0 :(得分:1)

也许您可以执行以下操作:

from django.http import HttpResponse, JsonResponse
 data = {
          "liked": liked,
          "updated": updated
        }       

if request.is_ajax:
  return JsonResponse(data, safe=False) #this is the response to ajax call

在ajax中:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);// here get the response from Django
    }
}
xhr.open('POST', 'my/url', true);
xhr.send(parameters);

要调用Ajax,您需要基于函数示例的视图:

myView(request):
 if request.is_ajax:
  .....
   ..