使用Django和Python创建Json response的方法
作者:fengyu09 时间:2022-04-28 13:08:42
使用jQuery的.post提交,并期望得到多个数据,Python后台要使用json格式。
不指定datatype为json,让jquery自行判断数据类型。(注:跨域名请求数据,则使用 jsonp字符串)
若post指定数据类型json,则python取post数据,我觉着麻烦。让jquery智能判断,python返回字典最方便。
一般使用字典,而不是列表来返回 JSON内容.
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 correct - not specifying the mimetype will get you into trouble
正确-不指定mimetype 会导致麻烦
content_type should be used now --mimetype is now deprecated
mimetype 不推荐使用,应当使用content_type 。
不使用content_type,则只能接收第1个字符串。
环境:
python 2.7.6
django 1.6
根据百度来的文章,使用 django的simplejson,也被IDE建议使用json。
post的回调函数,只需要 :
function(data,status){
if(status == 'success') {
alert(data.box);
}}
使用.号来进行得对应Key值。
前端和后端都指定utf-8编码,python返回中文,直接 {'status':'成功'},连u前缀都不用。
来源:https://blog.csdn.net/fengyu09/article/details/30785101#
标签:创建,Json,response,Django,Python
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python time模块之时间戳与结构化时间的使用
2024-01-02 09:07:51
![](https://img.aspxhome.com/file/2023/3/66383_0s.png)
mssql存储过程表名和字段名为变量的实现方法
2011-12-01 07:59:13
SQL Server 总结复习 (二)
2012-10-07 10:35:00
UTF-8转为GB2312编码的asp函数
2007-08-23 13:42:00
PyCharm-错误-找不到指定文件python.exe的解决方法
2022-04-20 00:48:10
![](https://img.aspxhome.com/file/2023/3/75293_0s.jpg)
asp,php,.net使用301重定向方法
2007-09-26 14:05:00
python爬取免费代理并验证代理是否可用
2021-12-24 20:02:48
Pytorch如何切换 cpu和gpu的使用详解
2023-08-22 03:30:11
excel导入到SQL Sever数据库
2008-03-25 10:24:00
CI框架整合smarty步骤详解
2023-11-14 11:18:11
Python中文件遍历的两种方法
2022-01-28 20:34:03
用ASP实现就MP3曲目信息的操作全攻略
2008-05-28 12:42:00
sqlserver 三种分页方式性能比较[图文]
2011-09-30 11:16:20
Python快速查找list中相同部分的方法
2021-01-28 17:26:00
![](https://img.aspxhome.com/file/2023/0/91890_0s.jpg)
python识别图像并提取文字的实现方法
2023-06-07 18:36:36
![](https://img.aspxhome.com/file/2023/3/85383_0s.jpg)
python中numpy.zeros(np.zeros)的使用方法
2023-10-08 17:40:07
Python中logging日志库实例详解
2023-10-04 13:26:25
TensorFlow卷积神经网络MNIST数据集实现示例
2023-04-20 18:33:12
基于Python快速处理PDF表格数据
2021-04-11 23:29:54
![](https://img.aspxhome.com/file/2023/1/99461_0s.jpg)
python3实现字符串操作的实例代码
2023-08-23 06:24:31