Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django to return json format data to prototype ajax

is there a way i can pass json format data through django HttpResponse. I am trying to call the view through prototype ajax and return json format data.

Thanks

like image 904
icn Avatar asked Nov 30 '22 10:11

icn


2 Answers

You could do something like this inside your app views.py

    import json

    def ajax_handler(req, your_parameter):

        json_response = json.dumps(convert_data_to_json)

        return HttpResponse(json_response,mimetype='application/json')
like image 117
Lombo Avatar answered Dec 10 '22 15:12

Lombo


Building on Lombo's answer, you might want to utilize the request.is_ajax() method. This checks the HTTP_X_REQUESTED_WITH header is XmlHttpRequest.

This is a good way to avoid sending a json response to a regular GET - which I guess at worst is just confusing to your users, but also lets you use the same view for ajax vs. non-ajax requests. This approach makes it easier to build apps that degrade gracefully.

For example:

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)

This approach works particularly well for form processing also.

like image 26
Chris Lawlor Avatar answered Dec 10 '22 17:12

Chris Lawlor