使用Django模板系统返回JSON响应 [英] Return JSON response using Django template system

查看:281
本文介绍了使用Django模板系统返回JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有可能吗? 我试过了:

Is it possible? I tried:

def jsonview(request):
  context = {}
  context['date'] = datetime.now()
  return render(request, "json.html", context, content_type="application/json")

json.html文件:

The json.html file:

{% load i18n %}

'{"date": "{{ date|escapejs }}", "test": "hello"}' 

响应为:

'\n\n{"date": "2014\u002D11\u002D13 11:58:31.635102", "test": "hello"}' 

所以错误是:

SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data

推荐答案

简单的方法是首先将模板中的数据呈现为字符串,然后像下面的示例代码一样将其作为json进行响应.

simple approach is to render first the data from your template to string and response it as json like the sample code below.

from django.template.loader import render_to_string
from django.http import HttpResponse
def jsonview(request):
      context = {}
      context['data'] = render_to_string("json.html", {'date': datetime.now()})
      return HttpResponse(json.dumps(context), content_type="application/json")

这篇关于使用Django模板系统返回JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆