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

yipeiwu_com6年前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设计】。

相关文章

tensorflow: 查看 tensor详细数值方法

问题 tensor详细数值 不能直接print打印: import tensorflow as tf x = tf.constant(1) print x 输出: Tensor...

对python字典元素的添加与修改方法详解

1、字典中的键存在时,可以通过字典名+下标的方式访问字典中改键对应的值,若键不存在则会抛出异常。如果想直接向字典中添加元素可以直接用字典名+下标+值的方式添加字典元素,只写键想后期对键赋...

对python读取CT医学图像的实例详解

对python读取CT医学图像的实例详解

需要安装OpenCV和SimpleItk。 SimpleItk比较简单,直接pip install SimpleItk即可。 代码如下: #coding:utf-8 import S...

python查找目录下指定扩展名的文件实例

本文实例讲述了python查找目录下指定扩展名的文件。分享给大家供大家参考。具体如下: 这里使用python查找当前目录下的扩展名为.txt的文件 import os items =...

Python cv2 图像自适应灰度直方图均衡化处理方法

Python cv2 图像自适应灰度直方图均衡化处理方法

__author__ = 'Administrator' import numpy as np import cv2 mri_img = np.load('mri_img.npy...