使用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设计】。

相关文章

python编程开发之类型转换convert实例分析

本文实例讲述了python编程开发之类型转换convert。分享给大家供大家参考,具体如下: 在python的开发过程中,难免会遇到类型转换,这里给出常见的类型转换demo:  ...

Python标准库之sqlite3使用实例

Python标准库之sqlite3使用实例

Python自带一个轻量级的关系型数据库SQLite。这一数据库使用SQL语言。SQLite作为后端数据库,可以搭配Python建网站,或者制作有数据存储需求的工具。SQLite还在其它...

python中模块的__all__属性详解

python模块中的__all__属性,可用于模块导入时限制,如: from module import * 此时被导入模块若定义了__all__属性,则只有__all__内指定的属...

Python中函数的参数传递与可变长参数介绍

Python中函数的参数传递与可变长参数介绍

1.Python中也有像C++一样的默认缺省函数 复制代码 代码如下: def foo(text,num=0):     print text,num fo...

python实现电子产品商店

python实现电子产品商店

利用python实现以下功能:基于python下的电子产品商店 电子产品商店 v0.1 请选择商品: ============================= 1  &nbs...