【问题标题】:Implement Ajax in a Django Project not working properly在 Django 项目中实现 Ajax 无法正常工作
【发布时间】:2020-11-18 02:53:37
【问题描述】:

我正在尝试使用 Ajax 为我的博客文章实现一个点赞按钮,我遇到了一个我无法修复的错误,因此我通过以下步骤多次从头开始:

  1. 创建 Post 模型和 Like 模型
  2. 添加了当我点击喜欢和不喜欢时当前运行良好的视图
  3. 我从post_detail.html 中提取了类似部分并将其添加到单独的html like_section.html
  4. 添加了正确值的 ajax

现在我的问题是,当我按下赞按钮时,会打开一个带有 ajax 输出的新页面

{"form": "....(html and ajax codes repeated)......"}

我的问题是如何解决此错误,以便在不刷新页面的情况下提交赞?

这里是 Posts.py 的模型

class Post(models.Model):
    ---------other attributed like: title, content, author, date_posted, slug-----
    likes = models.IntegerField(default=0)

class Like(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

以下是观点:

def like_post(request):
    user = request.user

    if request.method == 'POST':
        post = request.POST.get('post_id')
        post_obj = Post.objects.get(id=post)
        current_likes = post_obj.likes

        if user in post_obj.liked.all():
            post_obj.liked.remove(user)
            current_likes = current_likes - 1

        else:
            post_obj.liked.add(user)
            current_likes = current_likes + 1

        post_obj.likes=current_likes
        post_obj.save()

        like, created = Like.objects.get_or_create(user=user, post_id=post)
        if not created:
            if like.value == 'Like':
                like.value = 'Unlike'
            else:
                like.value = 'Like'
        like.save()
        context = {
            'post': post,
        }
    if request.is_ajax:
        html = render_to_string('blog/like_section.html',context, request=request)
        return JsonResponse({'form': html})

这是帖子的详细信息.html

        <!-- Like -->
        <div id="like-section">
        {% include 'blog/like_section.html' %}
        </div>
        <!-- Like -->

这里是like-section.html

          <form action="{% url 'blog:like-post' %}" method="POST" class="like-form" id="{{post.id}}">
            {% csrf_token %}
            <input type="hidden" name="post_id" value='{{post.id}}'>
            {% if user not in post.liked.all %}
              <button id="like" value='{{post.id}}' class="bwhite sm-button" style="color: grey; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none;">
                <i class="far fa-thumbs-up" type="submit"></i>
              </button>
            {% else %}
              <button id="like" value='{{post.id}}' class="bwhite sm-button" >
                <i class="far fa-thumbs-up" type="submit"></i>
              </button>
            {% endif %}
            <div class="like-count{{post.id}}">{{ post.num_likes }} Likes</div>
          </form>

这里是 ajax:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script>
      $(document).ready(function(event){
        $(document).on('click', '#like', function(event){
          event.preventDefault();
          var pk = $(this).attr('value');
          $.ajax({
            type: 'POST',
            url: '{% url "blog:like-post" %}',
            data: {'post_id':pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
            dataType: 'json',
            success: function(response){
              $('#like-section').html(response['form'])
              console.log($('#like-section').html(response['form']));
            },
            error: function(rs, e){
              console.log(rs.responseText);
            },
          });
        });
  </script>

这里是 urls.py

    path('blogs/like', like_post, name='like-post'),

【问题讨论】:

    标签: javascript jquery django ajax


    【解决方案1】:

    您正在返回一个 HTML 页面作为您的视图的响应,我认为这可能是导致它的原因。首先尝试返回类似 {"msg","worked"} 的内容,看看它是否有效

    【讨论】:

    • 我添加了return JsonResponse({'msg': 'worked'}),当我点击喜欢按钮时收到了{"msg": "worked"}
    • 为什么要在 Json 响应中以字符串形式返回 HTML 页面,看起来这就是问题所在。你为什么不直接返回帖子的点赞数
    • 当用户点击喜欢按钮时,我不希望它被刷新,以显示差异,所以我试图只返回喜欢部分,并从不喜欢更改为喜欢,无论数量如何喜欢的人
    • 是的,即使这样您也不需要返回整个 HTML 页面。在响应中只返回当前用户是否喜欢它,然后根据响应用 JS 更新按钮。如果您返回整个 HTML 页面,它将像以前一样在新页面中继续打开。
    猜你喜欢
    • 2021-10-03
    • 2017-06-18
    • 2018-12-03
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 2020-08-21
    • 2014-01-11
    相关资源
    最近更新 更多