为什么我的 http 响应一直显示为 html 页面?

Why does my http response keep showing like an html page?

事情是这样的:我认为我可以收到一个 HTTP 响应并用 javascript ajax 管理它,然后用那个响应做任何我想做的事而不用用户甚至注意到了。例如使用 console.log(response)。 但是 它不起作用 并且响应以文本形式显示,如 html。

我将解释我在做什么和我的问题: 我正在为 Django 应用程序制作评论部分。我的评论系统运行良好。用户可以 post 评论并查看其他人的评论。 问题是我每次都必须刷新页面才能加载最近发布的评论。

这不是很酷,我希望能够 post 评论并立即看到它而无需重新加载页面。 我做了我的研究并在 quora

上找到了这条评论

You use AJAX and a Django backend view. Something (a user leaving a new comment, a timer etc.) will trigger a JavaScript AJAX call to a Django view requesting comments for the page. That Django view will return the result to the JavaScript AJAX call. It can be done in two ways:

  1. it can just return the data, typically in JSON and then JavaScript worries about rendering that data on the page

  2. or, the view can run the data through a Django template and return the partial HTML and then the JavaScript just needs to swap out the HTML response chunk in the content area for the comments (typically identified by a HTML ID, where you replace the HTML content of the div with a certain ID with the HTML you received from the view both approaches have pros and cons and which is better depends on many factors

我正在尝试采用第二种方式。 我的问题是 HttpResponse 更改了我的整个页面并将响应中的内容显示为 html 文本!

这是我的 views.py。这是呈现评论部分所在页面的视图 (我还没有发送呈现的 html 因为我有 HTTP 响应问题)

def make_bid(request, pk):
    listing = Listing.objects.get(id = pk)
    comments = listing.comments.all()
    if request.method == "POST":
        if request.user.is_authenticated:
            comment = Comment(
                user = request.user,
                comment= request.POST['comment'],
                date = datetime.datetime.now().date(),
                listing = listing)
            comment.save()
            context = {'comments': listing.comments.all()}
            rendered = render_to_string("auctions/comments.html", context)
            return HttpResponse("this a http response")
        else:
            return HttpResponse("user is not even authenticated")
    else:
        return render(request, "auctions/make-bid.html", {
            'article' : listing,
            'comments': comments
        })

评论区html

    <aside class="comment__section">
        <h3>Comments</h3>
        <form action="{% url 'make-bid' article.id %}" method="post" id="form-comment">
            {% csrf_token%}
            <textarea id="textbox" class="field form__field--block" value="" name="comment" placeholder="What do you think about this listing?"></textarea>
            <input class="button button__primary" type="submit" value="Publish">
        </form>
        <section class="comment__container">
            <!-- comments from the http response should be inserted here with javascript-->
        </section>
    </aside>

javascript。我从另一个 Whosebug 问题中复制了这个。我自己用普通 javascript 做的,我认为这可能是问题所在。它不是。它仍然没有给我想要的结果

<script>
    aside = document.querySelector(".comment__section")
    // this is the id of the form
    $("#from-comment").submit(function(e) {

    e.preventDefault(); // avoid to execute the actual submit of the form.

    var form = $(this);
    var url = form.attr('action');

    $.ajax({
        type: "POST",
        url: url,
        data: form.serialize(), // serializes the form's elements.
        success: function(data)
        {
            alert(data); // show response from the php script.
            console.log('Submission was successful.');
            console.log(data);
        },
        error: function(data){
            console.log("no response")
        }
        });

    });


</script>

我已经尝试使用 return JsonResponse。结果还是一样:( 我真的迷路了。我对 Django 和服务器端的东西很陌生。而且我不知道为什么显示的响应像整页一样? 我错过了什么? http 响应是否真的像我认为的那样工作? 我真的很感激任何帮助。谢谢!!!

您必须序列化数据。意思是,将 django queryset 转换成 json 格式发送到 ajax.

from django.core import serializers

def make_bid(request, pk):
    listing = Listing.objects.get(id = pk)
    comments = listing.comments.all()
    if request.method == "POST":
        if request.user.is_authenticated:
            comment = Comment(
                user = request.user,
                comment= request.POST['comment'],
                date = datetime.datetime.now().date(),
                listing = listing)
            comment.save()
            comments = listing.comments.all()
            serialized_qs = serializers.serialize('json', list(comments))
            data = {"queryset" : serialized_qs}
            return JsonResponse(data)
        else:
            return HttpResponse("user is not even authenticated")
    else:
        return render(request, "auctions/make-bid.html", {
            'article' : listing,
            'comments': comments
        })

我修好了!我的主要问题是我。我犯了一些愚蠢的错误。我有一个错字,jquery 没有加载。下面是脚本现在的样子:

<script src="{%static 'auctions/scripts/jquery-3.6.0.js' %}"></script>
<script>
     $(document).ready(function(){


        $("#form-comment").submit(function(e) {

        e.preventDefault(); // avoid to execute the actual submit of the form.

        var form = $(this);
        var url = form.attr('action');

        $.ajax({
            type: "POST",
            url: url,
            data: form.serialize(), // serializes the form's elements.
            success: function(data)
            {
                $("#comments").html(data);
                $("#textbox").val('')
            },
            error: function(data){
                console.log("no response")
            }
            });
        });
        })
</script>

和views.py。现在我发送带有 HttpResponse

的渲染评论部分
def make_bid(request, pk):
    listing = Listing.objects.get(id = pk)
    context = {'comments': listing.comments.all()}
    rendered = render_to_string("auctions/comments.html", context)
    if request.method == "POST":
        if request.user.is_authenticated:
            comment = Comment(
                user = request.user,
                comment= request.POST['comment'],
                date = datetime.datetime.now().date(),
                listing = listing)
            comment.save()
            context = {'comments': listing.comments.all()}
            rendered = render_to_string("auctions/comments.html", context)
            return HttpResponse(rendered)
        else:
            return HttpResponse("user is not even authenticated")
    else:
        return render(request, "auctions/make-bid.html", {
            'article' : listing,
            'comments': rendered
        })

而html看起来像这样

    <aside class="comment__section" >
        <h3>Comments</h3>
        <form method="post" id="form-comment">
            {% csrf_token%}
            <textarea id="textbox" class="field form__field--block" value="" name="comment" placeholder="What do you think about this listing?"></textarea>
            <input class="button button__primary" type="submit" value="Publish">
        </form>
        <section class="comment__container" id="comments">
            {{comments}}
        </section>
    </aside>

我仍然希望看到一种方法来进行 ajax 调用并使用 javascript 处理响应。但我现在已经完成了这个评论部分! 感谢所有回答这个问题的人!