Django模板-Ajax响应-如何? [英] Django template - ajax response - how to?

查看:43
本文介绍了Django模板-Ajax响应-如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了一堆关于此的博客后,我找不到答案,同样也在SO中进行搜索.

After reading a bunch of blogs about this i can not find the answer, also searched in SO as well.

我有一个使用Django模板标签的模板:

I have a template that use django template tags:

<div class="box" id="dates">
     <h2 class="h2">Dates</h2>
          <ul class="list-group">
                {% for days in dates %}
                <li class="list-group-item list-group-item-success">{{ days }}</li>
                {% endfor %}
          </ul>
</div>

此div等待来自ajax响应的答案.这是ajax代码:

This div waits for an answer that comes from an ajax response. Here is the ajax code:

$("#formi").submit(function(event){
   event.preventDefault();
    var data = new FormData($('form').get(0));

        $.ajax({
             type:"POST",
             url:"{% url 'dates' %}",
             data: data,
             processData: false,
             contentType: false,
             csrfmiddlewaretoken: '{{ csrf_token }}',

             success: function(data){
                 console.log("YEEEEEEEEEEEEEEEEAAAAAAAAAAAHHHHHHHHHHHHHHHHHHHHHHHH")
                 $("#dates").html({{ data.dates }});
                },
        });
   });

漂亮的自我解释.它将表单发送到视图,该视图使用将用于填充模板中 for循环的数据响应json.

Pretty self explainatory. It sends a form to a view and the view responds a json with the data that is going to be used to fill the for loop in the template.

我可以看到数据正在进入控制台中的模板

I can see that the data is getting to the template in th console

但是您可以看到,这无法识别ajax成功中 $(#dates").html 之后的 {{data.dates}} 标记

But as u can see this is not recognizing my {{data.dates}} tag after $("#dates").htmlin the ajax succes

那么,我如何仍可以在模板中使用django标签,并从ajax响应中获取数据?

So, how can i still use this django tags in my template and get the data out of the ajax response?

在此先感谢您提供的任何帮助.

Thanks in advance for any help provided.

推荐答案

data 是纯文本,不是python变量,因此您无法在 {{}}中将其打印出来.它看起来像一个JSON对象,因此您可以执行以下操作:

data is a plain text, not a python variable so you can't print it out within {{ }}. It looks like a JSON object, so you can do the following:

假设您已安装 jQuery :

$.each(data.dates, function(i, val) {
    $('ul.list-group').empty().append(
        $('<li>').addClass('list-group-item list-group-item-success').text(val)
    )
});

这篇关于Django模板-Ajax响应-如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆