Hello! There is a form on search (I use without ajax ). The result is normal. I decided to use ajax and json . Question: how to return the data in json format, the documentation is a bit confused ...

As now I send:

  def dictfetchall(cursor): desc = cursor.description return [dict(zip([col[0] for col in desc], row))for row in cursor.fetchall()] if request.GET['searchType'] == 'FIO': cursor = connection.cursor() cursor.execute('SET NAMES utf8;') cursor.execute(sql2.format(request.GET.get('search','').encode("utf-8"))) return render(request, 'search/search.html', {'forms': SearchForm(), 'res': dictfetchall(cursor)}) 

    1 answer 1

    The simplest solution, "in the forehead":

     … data = {"res": dictfetchall(cursor)} # Если в адресе было «?json» (или «?json=1»), значит отдаем JSON. if request.GET.get("ajax", None) is not None: return HttpResponse(json.dumps(res), content_type="application/json") else: data["forms"] = SearchForm() return render_to_response("search/search.html", data) 

    ( HttpResponse in django.http )

    If this is necessary a lot and often - it is worth thinking about generalization, for example, in the spirit of something like this decorator:

     def template_or_json(template_name): def __decorator(f): @wraps(f) def __wrapper(request, *args, **kwargs): data = f(request, *args, **kwargs) if request.GET.get("json", None) is not None: return HttpResponse(json.dumps(data), content_type="application/json") else: return render_to_response(template_name, data, context_instance=RequestContext(request)) return __wrapper return __decorator 

    And further

     @template_or_json("search/search.html") def my_view(request): ... return {"res": dictfetchall(cursor)} 

    (In the code there may be irrelevant typos or clerks, I write as a keepsake, did not check.)

    • The data does not come in json. - avdoshkin
    • And more specifically, please? How do you request them and what do you get? It should be, for example, something like this (option on the bare jQuery): $ .getJSON ("...? Json = 1", function (data) {console.log (data.res);}); Yes, and I just noticed a mistake, corrected the decorator. If the variant with it was used - I forgot json.dumps there. - drdaeman
    • I see that ajax came, but I get the data in get and send it in json format. Maybe in terminology I am a little mistaken. with ajax and json and the adjacent buns for the first time ...) - avdoshkin
    • The script did not enter here, sent to you personally in vk. - avdoshkin pm
    • (Copied here: pastebin.com/R0TkyB5h ) Looks right, but what's coming? Error (alert) or what in the console? HttpResponse(json.dumps(data), ...) should give to JSON. You can change the content_type="text/plain" and open the URL directly in the browser (past $.ajax and see what $.ajax ). - drdaeman