Django returns json format data for ajax prototype

Is there any way to pass json format data via django HttpResponse. I am trying to call a view through an ajax prototype and return json format data.

thank

+3
source share
2 answers

You can do something like this in your views.py application

    import json

    def ajax_handler(req, your_parameter):

        json_response = json.dumps(convert_data_to_json)

        return HttpResponse(json_response,mimetype='application/json')
+14
source

Based on Lombo's answer you can use a method request.is_ajax(). This checks the HTTP_X_REQUESTED_WITH: XmlHttpRequest header.

json- GET, , , , ajax non-ajax-. , .

:

def your_view(request):
    data_dict = # get some data

    if request.is_ajax():
        # return json data for ajax request
        return HttpResponse(json.dumps(data_dict),mimetype='application/json')

    # return a new page otherwise
    return render_to_response("your_template.html", data_dict)

.

+6

Source: https://habr.com/ru/post/1753449/