问题
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.
回答1:
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)
)
});
回答2:
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);
来源:https://stackoverflow.com/questions/32790538/django-template-ajax-response-how-to