how to loop ajax response data in Django template language?

▼魔方 西西 提交于 2021-01-29 13:50:58

问题


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


回答1:


You need to use JsonResponse in your view.

>>> from django.http import JsonResponse
>>> response = JsonResponse({'foo': 'bar'})
>>> response.content
b'{"foo": "bar"}'

or for dict

response = JsonResponse([1, 2, 3], safe=False)

https://docs.djangoproject.com/en/3.0/ref/request-response/

en than with jQuery

success: function (data) {
   $.each(data.data, function(k, v) {
       /// do stuff
   });
}



回答2:


An alternative approach to what NKSM has suggested would be to return a partial view and inject the html in.

Your view:

def process_data(request):
    return render(request, 'partials/process_data.html', context={
        'data': [1, 2, 3],
    })

partials/process_data.html template

{% for key in data %}
    <p>{{ key }}</p>
{% endfor %}

Then your loading JS turns into

var container = $('#some-container')
container.load('/processData', {foo: "this is required to force a post rather than get")


来源:https://stackoverflow.com/questions/59306649/how-to-loop-ajax-response-data-in-django-template-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!