如何以Django模板语言循环ajax响应数据? [英] how to loop ajax response data in Django template language?
问题描述
我是Django的新手,最近遇到一个问题:众所周知,在html中循环通过视图发送的数据很简单,如下所示:
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 %}
但是,在没有刷新网页的情况下循环Ajax发送的数据该怎么办?
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?
}
})
您知道传统方式是使用Jquery每个函数附加标签,如下所示
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 %}
});
}
但是,我迷上了用Django模板语言解决问题的方法你能告诉我如何解决吗?谢谢,如果您有任何想法!
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!!
推荐答案
NKSM建议的另一种方法是返回部分视图并将html注入其中.
An alternative approach to what NKSM has suggested would be to return a partial view and inject the html in.
您的视图:
def process_data(request):
return render(request, 'partials/process_data.html', context={
'data': [1, 2, 3],
})
partials/process_data.html模板
partials/process_data.html template
{% for key in data %}
<p>{{ key }}</p>
{% endfor %}
然后您正在加载的JS变成
Then your loading JS turns into
var container = $('#some-container')
container.load('/processData', {foo: "this is required to force a post rather than get")
这篇关于如何以Django模板语言循环ajax响应数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!