首页 > 编程 > Python > 正文

使用Django和Python创建Json response

2019-11-08 20:22:26
字体:
来源:转载
供稿:网友

使用jQuery的.post提交,并期望得到多个数据,Python后台要使用json格式。

不指定datatype为json,让jquery自行判断数据类型。(注:跨域名请求数据,则使用 jsonp字符串)

若post指定数据类型json,则python取post数据,我觉着麻烦。让jquery智能判断,python返回字典最方便。

一般使用字典,而不是列表来返回 JSON内容.

[python] view plain copy 在CODE上查看代码片import json  from django.http import HttPResponse    response_data = {}  response_data['result'] = 'failed'  response_data['message'] = 'You messed up'  return HttpResponse(json.dumps(response_data), content_type="application/json")  

for%20correct%20-%20not%20specifying%20the%20mimetype%20will%20get%20you%20into%20trouble

正确-不指定mimetype%20会导致麻烦

content_type%20should%20be%20used%20now%20--mimetype%20is%20now%20deprecated

mimetype%20不推荐使用,应当使用content_type

不使用content_type,则只能接收第1个字符串。

环境:

python%202.7.6

django%201.6

根据百度来的文章,使用%20django的simplejson,也被IDE建议使用json。

post的回调函数,只需要%20:

[python]%20view%20plain%20copy%20派生到我的代码片function(data,status){       if(status == 'success') {               alert(data.box);            }}  使用.号来进行得对应Key值。

前端和后端都指定utf-8编码,python返回中文,直接 {'status':'成功'},连u前缀都不用。


上一篇:python学习笔记

下一篇:Python安装easygui

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表