使用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模拟GitHub登录详解

如何利用Python模拟GitHub登录详解

前言 最近学习了Fiddler抓包工具的简单使用,通过抓包,我们可以抓取到HTTP请求,并对其进行分析。现在我准备尝试着结合Python来模拟GitHub登录。 Fiddler抓包分析...

python利用7z批量解压rar的实现

一开始我使用了rarfile这个库,奈何对于含有密码的压缩包支持不好,在linux上不抛出异常;之后有又尝试了unrar。。比rarfile还费劲。。 所以用了调用系统命令的方法,用7z...

django 2.2和mysql使用的常见问题

可能是由于Django使用的MySQLdb库对Python3不支持,我们用采用了PyMySQL库来代替,导致出现各种坑,特别是执行以下2条命令的是时候: python manage....

pytorch标签转onehot形式实例

代码: import torch class_num = 10 batch_size = 4 label = torch.LongTensor(batch_size, 1).ran...

Python基于Pymssql模块实现连接SQL Server数据库的方法详解

Python基于Pymssql模块实现连接SQL Server数据库的方法详解

本文实例讲述了Python基于Pymssql模块实现连接SQL Server数据库的方法。分享给大家供大家参考,具体如下: 数据库版本:SQL Server 2012。 按照Python...