使用Django和Python创建Json response的方法

yipeiwu_com5年前Python基础

使用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前缀都不用。

以上这篇使用Django和Python创建Json response的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Pytorch 实现冻结指定卷积层的参数

python代码 for i, para in enumerate(self._net.module.features.parameters()): if i &...

selenium+python 对输入框的输入处理方法

最近自己在做项目的自动化测试(公司无此要求),在用户管理模块做修改用户信息时,脚本已经跑成功,并且的确做了update操作,但是自己登陆页面检查,信息却没有被修改,再次确定系统该模块的编...

Python中使用Tkinter模块创建GUI程序实例

使用Tkinter模块来创建简单的GUI程序。 Tkinter的Widgets有:Button、Canvas、Checkbutton、Entry、Frame、Label、Listbox、...

Python二进制文件读取并转换为浮点数详解

Python二进制文件读取并转换为浮点数详解

本文所用环境: Python 3.6.5 |Anaconda custom (64-bit)| 引言 由于某些原因,需要用python读取二进制文件,这里主要用到struct包,而这...

Python实现决策树并且使用Graphviz可视化的例子

Python实现决策树并且使用Graphviz可视化的例子

一、什么是决策树(decision tree)——机器学习中的一个重要的分类算法 决策树是一个类似于数据流程图的树结构:其中,每个内部节点表示一个属性上的测试,每个分支代表一个属性输出,...