简体   繁体   中英

ajax response return with function for

Can you tell me how can I replace code html with function 'for from django'?

$.ajax({                                                                                                                           
    url: url,
    data: $('#FormSite').serialize(), 
    type: "POST",
    async:false,
    success: function(response) {
        $($("#Pic").first()).replaceWith($(response['Pic']));
        $("#HeaderWpis").text(response['h1']);
        $("#WpisChild").html("<div id='WpisChild'> {% for News in Messags %} <p>{{ News.title }}</p> </div>");
    },
    error: function(data)
    {
        alert('Bad connection');
        console.log(data);
    }

});

When I do this I got {%for%} from third div 'WpisChild' as text. The function does not perform on the page. Could you tell me why?

The Django template language is processed when your views are accessed, so JQuery can't interpret it. Here are two suggestions:

  1. Create the HTML with the Django template language by using the render() function in your views.py file. You will need to create a new template with that HTML segment and direct the AJAX call to a new view. The Messages would be passed to the template as the context and the {% for %} loop will work. The response will be the fully constructed HTML which you can then.append() to the chosen div.
def get_messages(request):
    if request.method == 'POST':
        # do whatever with your request, fetch your messages

        context = {
            'Messages': messages
        }
        return render(request, 'message-template.html', context)
$("#WpisChild").append(response)
  1. Include the Messages data in your existing response, loop through the list and append each one as an element to the div. This option might be preferred if your response has other data.
response['Messages'].forEach(function(news) {
    $("#WpisChild").append('<p>' + news.title + '</p>')
});

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