Ajax,Django:状态 200 但抛出错误而不是成功

bkr*_*rop 7 django ajax django-templates django-views

我正在尝试使用 ajax 发表评论,但它不起作用。当我按下按钮控制台未打印任何错误(如 404 等)时,未发布评论。错误返回的对象:

{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, ...} abort: ƒ (e) always: ƒ () catch: ƒ (e) done: ƒ () fail: ƒ () getAllResponseHeaders: ƒ () getResponseHeader: ƒ (e) overrideMimeType: ƒ (e) pipe: ƒ () progress: ƒ () promise: ƒ (e) readyState: 4 responseText: "?" setRequestHeader: ƒ (e,t) state: ƒ () status: 200 statusCode: ƒ (e) statusText: "OK" then: ƒ (t,n,r) proto : Object

在命令行中我看到:

“POST / HTTP/1.1” 200 5572

当我将按钮更改为“提交”时,它会使用正确的 JSON 进行发布和响应,例如:

{"comment": {"id": 16, "author": 1, "content": "test", "post": 12}}

我的代码如下,任何帮助表示赞赏:

视图.py

def homepage(request):
    profiles = Follow.objects.filter(follow_by=request.user.profile).values_list('follow_to', flat=True)
    posts = Post.objects.filter(author_id__in=profiles).order_by('-date_of_create')
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            pk = request.POST.get('pk')
            post = Post.objects.get(pk=pk)
            new_comment = Comment.objects.create(
                author = request.user.profile,
                post = post,
                content = form.cleaned_data['content']
            )
            return JsonResponse({'comment': model_to_dict(new_comment)}, status=200)
    form = CommentForm()
    context = {
        'posts': posts,
        'form': form
    }
    return render(request, 'posts/homepage.html', context=context)
Run Code Online (Sandbox Code Playgroud)

模板

<div class="comments" id="{{ post.pk }}" style="display: none">
            {% include 'posts/comments.html' %}
            <form action="" method="post" class="commentForm" data-url="{% url 'post_comments' post.pk %}">
                {% csrf_token %}
                <input type="hidden" name="pk" value="{{ post.pk }}">
                {{ form.as_p }}
                <button type="button" class="commentBtn" id="{{ post.pk }}">Comment</button>
            </form>
Run Code Online (Sandbox Code Playgroud)

添加评论.js

$(document).ready(function () {
    $('.commentBtn').click(function () {
        let serializedData = $('.commentForm').serialize();
        let btn = $(this);
        let id = btn.attr('id');
        console.log($(".commentForm").data('url'));
        $.ajax({
            url: $(".commentForm").data('url'),
            data: serializedData,
            type: 'post',
            dataType: 'json',
            success: function (data) {
                console.log(data);
                $(`#${id}.comments`).load('/posts/comments/' + data.post);
                $('textarea').val('');
            },
            error: function(textStatus) {
                console.log(textStatus)
            }
        })
    })
})
Run Code Online (Sandbox Code Playgroud)

编辑:我使用了这个问题:Ajax 请求返回 200 OK,但是一个错误事件被触发而不是成功 ,删除dataType: 'json'并添加contentType: 'application/json' ,现在我收到 403 错误。

Swa*_*ati 4

由于您已经习惯$('.commentForm')将表单数据发送到后端,它将获取具有类的所有表单commentForm并发送所有表单的数据,这就是它不起作用的原因。相反,您可以将其更改$('.commentForm').serialize() $(this).closest(".commentForm").serialize()

另外,您正在使用#${id}.commentsajax 的内部 success 函数,这将覆盖内部的任何内容#${id}.comments并从 url 加载新内容,即:/posts/comments/..。因此,为了避免这种情况,一种方法是{% include 'posts/comments.html' %}用一些外部 div 包围您,然后更改您的选择器,即:#${id}.comments > .yourouterdivclassname新内容才会被加载到里面,div这样表单就不会被删除。