skip to Main Content

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


  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
       });
    }
    
    Login or Signup to reply.
  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")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search