简体   繁体   English

ajax 响应返回 function 为

[英]ajax response return with function for

Can you tell me how can I replace code html with function 'for from django'?你能告诉我如何用 function '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);
    }

});

When I do this I got {%for%} from third div 'WpisChild' as text.当我这样做时,我从第三个 div 'WpisChild' 中得到 {%for%} 作为文本。 The function does not perform on the page. function 不在页面上执行。 Could you tell me why?你能告诉我为什么吗?

The Django template language is processed when your views are accessed, so JQuery can't interpret it.访问视图时会处理 Django 模板语言,因此 JQuery 无法解释它。 Here are two suggestions:这里有两个建议:

  1. Create the HTML with the Django template language by using the render() function in your views.py file.在您的views.py 文件中使用render() function 使用Django 模板语言创建HTML。 You will need to create a new template with that HTML segment and direct the AJAX call to a new view.您需要使用该 HTML 段创建一个新模板,并将 AJAX 调用定向到新视图。 The Messages would be passed to the template as the context and the {% for %} loop will work.消息将作为上下文传递给模板,{% for %} 循环将起作用。 The response will be the fully constructed HTML which you can then.append() to the chosen div.响应将是完整构造的 HTML ,然后您可以将其附加到所选的 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.在现有响应中包含消息数据,循环遍历列表和 append 每个作为 div 的元素。 This option might be preferred if your response has other data.如果您的响应包含其他数据,则可能首选此选项。
response['Messages'].forEach(function(news) {
    $("#WpisChild").append('<p>' + news.title + '</p>')
});

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

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