【问题标题】:Ajax not updating the div in DjangoAjax 没有更新 Django 中的 div
【发布时间】:2020-07-04 13:10:21
【问题描述】:

我在我的博客中使用 Ajax 作为按钮。当我点击Like 按钮时,数据库中的计数会更新,但不会反映在我的页面中(该按钮应更改为'Unlike' 而无需重新加载页面)。但是,当我刷新页面时,它会按预期反映。

views.py:

def like_post(request):
    user = request.user
    post_id = request.POST.get('id')
    post_obj = get_object_or_404(Post, id=post_id)

    if user in post_obj.liked.all():
        post_obj.liked.remove(user)
    else:
        post_obj.liked.add(user)

    like, created = Like.objects.get_or_create(user=user, post_id=post_id)

    if not created:
        if like.value == 'Like':
            like.value = 'Unlike'
        else:
            like.value = 'Like'

    like.save()
    context={
    'post': post_obj
    }

    if request.is_ajax():
        html = render_to_string('blog/like_section.html', context, request=request)
        return JsonResponse({'form': html})

阿贾克斯:

<script
  src="https://code.jquery.com/jquery-3.5.1.js"
  integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
  crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(document).ready(function(event){
            $(document).on('click', '#like', function(event){
                event.preventDefault();
                var pk = $(this).attr('value');
                $.ajax({
                    type : 'POST',
                    url : {% url 'like-post' %},
                    data : {'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>

HTML:

<form action="{% url 'like-post' %}" method="POST">
      {% csrf_token %}
      {% if user not in post.liked.all %}
        <button id="like" name="post_id" value="{{ post.id }}" class="btn btn-outline-info mb-4" type="submit">Like</button>
      {% else %}
        <button id="like" name="post_id" value="{{ post.id }}" class="btn btn-info mb-4" type="submit">Unlike</button>
      {% endif %}

</form>

urls.py:

path('likes/', views.like_post, name='like-post'),

控制台也没有错误

jQuery.fn.init {}
XHR finished loading: POST "http://localhost:8000/likes/".

【问题讨论】:

  • response['form'] 返回什么?它是否显示正确的按钮?
  • 为什么要将整个表单作为 json 响应而不是喜欢或不喜欢的字符串返回,并且在成功函数中为按钮 html 设置该值
  • 我是一个初学者,我跟随 Youtube 并得到了这个。如果有其他选择,请告诉我。
  • 看起来,有些问题成功了。我尝试在ajax中注释成功,结果和现在一样。

标签: python jquery django ajax django-views


【解决方案1】:

我可以通过在响应函数中重新加载 div 来获得结果。

success : function(response){
                 $(".like-section").load(" .like-section")
                 },

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多