开发者

django to return json format data to prototype ajax

开发者 https://www.devze.com 2023-01-06 10:44 出处:网络
is there a way i can pass开发者_如何学JAVA json format data through django HttpResponse. I am trying to call the view through prototype ajax and return json format data.

is there a way i can pass开发者_如何学JAVA json format data through django HttpResponse. I am trying to call the view through prototype ajax and return json format data.

Thanks


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')


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消