简体   繁体   English

在 AJAX POST 之后渲染 Django 模板

[英]Render Django Template after AJAX POST

I'm using django and ajax to build a small app.我正在使用djangoajax构建一个小应用程序。

I send some data by ajax:我通过 ajax 发送了一些数据:

// send search post when clicking the button
$("#search-button").click(function(){
    $.post(
        "{% url 'search-index' %}",
        {
            query: $("#query").val()
        },
        function(data, status){
            console.log("success")
        }
    )
})

And I generate some new data according to the query , which I'd like to display in the html template:我根据query生成了一些新数据,我想在 html 模板中显示:

def view(request):
    if request.method == "POST":
        query = request.POST["query"]
        hits = search(query)

        return render(request, "search/index.html", {"hits": hits})
{% if hits %}
    <div class="container">
    {% for hit in hits %}
        <div>
            <a href="">{{ hit.title }}</a>
        </div>
        <div>
            <p>{{ hit.abstract }}</p>
        </div>
    {% endfor %}
    </div>
{% endif %}

However, I find django is not rendering the template, I got an empty html page after this post request.但是,我发现django没有渲染模板,在这个帖子请求之后我得到了一个空的 html 页面。 I don't want to append the data using jquery.我不想 append 使用 jquery 的数据。 I prefer to modify the html in the template.我更喜欢修改模板中的html。

Any solution?有什么解决办法吗? Thanks in advance.提前致谢。

I found it is actually impossible .我发现这实际上是不可能的。 The django template is rendered from the serve side, while the ajax is parsed from the client side and is asynchronous. django 模板是从服务端渲染的,而 ajax 是从客户端解析的并且是异步的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM