views:

58

answers:

2

Hi all,

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

+6  A: 

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')
Lombo
+1  A: 

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.

Chris Lawlor
thanks for info!
xlione