簡體   English   中英

在 django 中無法使用 AJAX 獲取評論 ID

[英]Can not get comment id with AJAX in django

我在幾天內都在與這個問題作斗爭,但找不到適合我的情況的解決方案。 我正在嘗試在不刷新頁面的情況下制作喜歡系統。 在喜歡和不喜歡的同步模式下工作正常,但是當我嘗試添加 AJAX 時,我得到 405,並且只有最后一條評論可以單擊,我理解問題 Ajax 不理解 Z2B9AFB89A6ACC1575Burl 與 5BFidCA381或 pk 喜歡我的變體 {% url 'store:like' comment.pk %},但如何解決?

模板中有這一部分:

{% for comment in comments %}
       <h6 class="card-header">
       {{ comment.author }}<small> добавлен {{ comment.created_at|date:'M d, Y H:i' }} </small>
       </h6>
        <div class="card-body">
        <h4>{{ comment }}</h4>
        <form id="like" method="POST" data-url="{% url 'store:like' comment.pk %}">
                    {% csrf_token %}
                    <input type="hidden" value="{{comment.pk}}" name="id">
                    <input type="hidden" name="next" value="{{ request.path }}">
                    <button style="background-color: transparent; border: none; box-shadow: none;" type="submit">
                        <a class="btn btn-success" id="like"> Likes {{ comment.likes.all.count }}</a>
                    </button>
                </form>
        

        </div>
        {% empty %}
        <p>Для данного товара  ещё нет комментариев.</p>

        {% endfor %}

我的 ajax 在同一模板中調用:

<script type="text/javascript">
    $(document).ready(function(){

        var endpoint = $("#like").attr("data-url")

  $('#like').submit(function(e){

            e.preventDefault();

            var serializedData = $(this).serialize();
      $.ajax({
               type: 'POST',
               url: endpoint,
               data: serializedData,
               success: function(response) {
                     $('#main').load(' #main', function(){
           /// can add another function here

      });
                },
                error: function(rs, e) {
                       alert(rs.responseText);
                }
          });
    })

    });

這部分來自網址:

path('products/<int:pk>/like/', addlike, name='like'),

查看喜歡:

def addlike(request, *args, **kwargs):

        #is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
        #if request.method == 'POST' and is_ajax:

            pk = request.POST.get('id')
            post = Comment.objects.get(pk=pk)


            is_dislike = False

            for dislike in post.dislikes.all():
                if dislike == request.user:
                    is_dislike = True
                    break

            if is_dislike:
                post.dislikes.remove(request.user)

            is_like = False

            for like in post.likes.all():
                if like == request.user:
                    is_like = True
                    break

            if not is_like:
                post.likes.add(request.user)

            if is_like:
                post.likes.remove(request.user)


            next = request.POST.get('next', '/')
            return HttpResponseRedirect(next)
            #return JsonResponse({"success": True}, status=200)

        #else:
            #return JsonResponse({"success": False}, status=400)

如何強制 AJAX 調用我需要的 pk?

I think you should send the csrf_token with the ajax request add headers: { "X-CSRFToken": token } to your ajax request, "token is the csrf_token" or add @csrf_exempt decorator to your function but it will keep your view unsafe against CSRF 攻擊。

你可以在這里找到更多信息https://docs.djangoproject.com/en/4.0/ref/csrf/

去掉data-url並設置action屬性,因為當你點擊提交按鈕時,默認這個POST請求會被發送到當前的 URL 並且你會收到 405 狀態碼,但是如果你設置了action這個POST請求將會被發送對 url 之like的:

<form id="like" method="POST" action="{% url 'store:like' comment.pk %}">
    {% csrf_token %}
     <input type="hidden" value="{{comment.pk}}" name="id">
     <input type="hidden" name="next" value="{{ request.path }}">
     <button style="background-color: transparent; border: none; box-shadow: none;" type="submit">
     <a class="btn btn-success" id="like"> Likes {{ comment.likes.all.count }}</a>
     </button>
</form>
        

在js中你可以像這樣得到URL

var endpoint = $(this).attr('action');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM