显示JSON d

2024-05-05 23:32:39 发布

您现在位置:Python中文网/ 问答频道 /正文

在django my视图.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})

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


Tags: todjangofrompyimport视图jsonobj
1条回答
网友
1楼 · 发布于 2024-05-05 23:32:39

我不明白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

^{pr2}$

并使用如下命令:return JSONResponse(obj)

这在django1.7中默认添加了:https://docs.djangoproject.com/en/1.7/ref/request-response/#jsonresponse-objects

相关问题 更多 >