[ajax response return with function for

问题描述 投票:0回答:1

您能告诉我如何用'for from django'函数替换html代码吗?

$.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);
    }

});

[执行此操作时,我从第三格'WpisChild'中获得了{%for%}作为文本。该功能不在页面上执行。你能告诉我为什么吗?

javascript django ajax
1个回答
0
投票

访问视图时将处理Django模板语言,因此JQuery无法解释它。这里有两个建议:

  1. 通过在views.py文件中使用render()函数,使用Django模板语言创建HTML。您将需要使用该HTML段创建一个新模板,并将AJAX调用定向到新视图。消息将作为上下文传递到模板,并且{%for%}循环将起作用。响应将是完全构造的HTML,然后您可以将.append()到选定的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. 在现有响应中包括消息数据,在列表中循环,并将每个作为元素添加到div。如果您的回复中包含其他数据,则可能会首选此选项。
response['Messages'].forEach(function(news) {
    $("#WpisChild").append('<p>' + news.title + '</p>')
});
© www.soinside.com 2019 - 2024. All rights reserved.