如何动态更新模板中的对象?

2024-09-29 16:30:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我对页面上的产品有评论。还有一个添加注释的按钮,可以将新注释放入数据库。如何在页面上自动显示新注释

mytemplate.html

<div id="comments">
{% include 'comments.html' %}
</div>

comments.html

{% for comment in comments %}
        <!-- some code for display comments -->
{% endfor %}

script.js

$("#addComment").on("click", function(e){
        e.preventDefault()
        if ($("#addCommentArea").val() != ""){
            data = {
                commentText: $("#addCommentArea").val(),
                product_id: "{{ product.id }}"
            }
            $.ajax({
                type: "GET",
                url: "{% url 'newcomment' %}",
                datatype: 'json',
                data: data,
                success: function(data){
                    $("#addCommentArea").val("")
                }
            })
        }
    })

视图.py

class CommentView(View):
    def get(self, request):
        commentText = request.GET.get("commentText")
        if (len(commentText) > 0):
            newComment = Comment()
            newComment.Author = request.user
            product_id = request.GET.get("product_id")
            product = Product.objects.get(id=product_id)
            newComment.Product = product
            newComment.Comment = commentText
            newComment.save()
        return JsonResponse({'ok': 'ok'})

Tags: dividfordatagetrequesthtmlval
1条回答
网友
1楼 · 发布于 2024-09-29 16:30:09

目前,您只需呈现模板一次并获取注释,然后使用Ajax提交,这意味着您的模板不会得到更新。要在不刷新页面的情况下更新注释,您可以进行javascript轮询或使用例如web套接字

相关问题 更多 >

    热门问题