简体   繁体   中英

Django template - ajax response - how to?

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

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>

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 }});
                },
        });
   });

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

在此处输入图片说明

在此处输入图片说明

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

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 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:

Assuming you have jQuery installed:

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

All of the Django templates are rendered as html and js before the page loads, which means that {{ data.dates }} will return nothing because you don't have any data variable in your python code. Because of that you accept .html() in your js code.

data is a js object so you can simply do this:

$("#dates").html(data.dates);

But if you want to keep the old template in the #dates div you need to write:

var html = "";
$(data.dates).each(function(i, days){
    html += "<li class='list-group-item list-group-item-success'>"+days+"</li>"
});
$("#dates>ul").html(html);

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