显示JSON数据

时间:2014-05-02 06:53:51

标签: python django

在django我的view.py是

import json      
from django.http import HttpResponse
from django.template import Template, Context
from django.shortcuts import render_to_response

def ajax(request):
    obj =[dict(a = 1,b = 2)]
    jsons=json.dumps(obj)
    print jsons 
    return render_to_response("2.html", {"obj_as_json": jsons})

我想在我的模板2.html中显示a和b的值是JSON。请帮我写代码。

1 个答案:

答案 0 :(得分:1)

我不了解View的用法。

为什么要在模板渲染时将JSON对象作为上下文值传递?

标准是当您执行Ajax请求时,其响应应该是JSON响应,即mimetype = application / json

所以,你应该正常渲染模板并将结果转换为JSON并返回。 e.g:

def ajax(request):
    obj = {
       'response': render_to_string("2.html", {"a": 1, "b": 2})
    }
    return HttpResponse(json.dumps(obj), mimetype='application/json')

您可以创建一个类似于HttpResponse的JSONResponse类,使其成为通用的。 e.g。

class JSONResponse(HttpResponse):
    """
        JSON response
    """
    def __init__(self, content, mimetype='application/json', status=None, content_type=None):
        super(JSONResponse, self).__init__(
            content=json.dumps(content),
            mimetype=mimetype,
            status=status,
            content_type=content_type,
        )

并使用:return JSONResponse(obj)

默认情况下,这已在django 1.7中添加:https://docs.djangoproject.com/en/1.7/ref/request-response/#jsonresponse-objects