i am new to Django,recently meet a problem :as we know , to loop a data sent by view in html is simple , like below:
{% for key in data %}
<p>{{ key }}</p>
{% endfor %}
but ,what about loop a data sent by Ajax without refresh webpage?
$.ajax({
data:{"data":data},
url:'/processData/',
type: 'POST',
success: function (data) {
//how to re-loop above piece code?
}
})
You know the traditional way would be use Jquery each function to append tags, like below
success: function (data) {
$(data).each(function (index, obj) {
//process obj ,add tags,so as to simulate the effect of {% for i in data %}
});
}
But , i am obsessed with way to solve it by django template language
could you please tell how to solve it ? thanks if you have any ideas!!
2
Answers
You need to use JsonResponse in your view.
or for dict
https://docs.djangoproject.com/en/3.0/ref/request-response/
en than with jQuery
An alternative approach to what NKSM has suggested would be to return a partial view and inject the html in.
Your view:
partials/process_data.html template
Then your loading JS turns into