简体   繁体   中英

Render Django Template after AJAX POST

I'm using django and ajax to build a small app.

I send some data by 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:

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. I don't want to append the data using jquery. I prefer to modify the html in the template.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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