How to return json dictionary in django ajax update

I ask this question several times since I have not received any applicable help.

My problem is that I do not know how to return the result of the request to the template as an ajax response.

I have done this:

if request.path == "/sort/":
    sortid = request.POST.get('sortid')
    locs = Location.objects.order_by(sortid)
    if request.is_ajax():
        return HttpResponse(locs,mimetype="application/json")

then my ajax function donedoes this:

}).done(function(data){
$('.sortierennach').html(data);
});

what happens is that it just replaces the contents .sortierennach, this is not a django dic rendering, so I can do this:

{% for loc in locs %}
  {{loc.name}}
{% endfor %}

can someone please help me ... thank you very much

+5
source share
2 answers

You will need to export the list of objects to the JSON dictionary.

if request.path == "/sort/":
    sortid = request.POST.get('sortid')
    locs = Location.objects.order_by(sortid)
    if request.is_ajax():
        import json
        return HttpResponse(json.dumps(locs), mimetype="application/json")

However, you will need to use some client-side template system.

Django render_to_response. JSON. .

, AJAX. - , HTML, AJAX. - , , .

, my object_list.html:

<ul id='object-list'>
    {% for object in object_list %}
        <li>{{ object.value }}</li>
    {% endfor %}
</ul>

base.html:

<html>
<title>Example</title>
    <body>
        {% include 'object_list.html' %}
    </body>
</html>

:

from django.shortcuts import render_to_response
from django.template import RequestContext

from models import Location

def view(request):
    locs = Location.objects.order_by(sortid)
    if request.is_ajax():
        return render_to_response('object_list.html', {'object_list': locs}, context_instance=RequestContext(request))
    return render_to_response('base.html', {'object_list': locs}, context_instance=RequestContext(request))

GET XHTTP, HTML, . Handy!

+4

ajax, queryset json,

if request.path == "/sort/":
    sortid = request.POST.get('sortid')
    locs = Location.objects.order_by(sortid)
    if request.is_ajax():
        locs = json.dumps(locs)
        return HttpResponse(locs,mimetype="application/json")

ajax json.

, locs, html Ajax , .

+1

All Articles