使用Django和Python創(chuàng)建Json response的方法
使用jQuery的.post提交,并期望得到多個(gè)數(shù)據(jù),Python后臺(tái)要使用json格式。
不指定datatype為json,讓jquery自行判斷數(shù)據(jù)類型。(注:跨域名請(qǐng)求數(shù)據(jù),則使用 jsonp字符串)
若post指定數(shù)據(jù)類型json,則python取post數(shù)據(jù),我覺著麻煩。讓jquery智能判斷,python返回字典最方便。
一般使用字典,而不是列表來(lái)返回 JSON內(nèi)容.
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 會(huì)導(dǎo)致麻煩
content_type should be used now --mimetype is now deprecated
mimetype 不推薦使用,應(yīng)當(dāng)使用content_type 。
不使用content_type,則只能接收第1個(gè)字符串。
環(huán)境:
python 2.7.6
django 1.6
根據(jù)百度來(lái)的文章,使用 django的simplejson,也被IDE建議使用json。
post的回調(diào)函數(shù),只需要 :
function(data,status){
if(status == 'success') {
alert(data.box);
}}
使用.號(hào)來(lái)進(jìn)行得對(duì)應(yīng)Key值。
前端和后端都指定utf-8編碼,python返回中文,直接 {'status':'成功'},連u前綴都不用。
以上這篇使用Django和Python創(chuàng)建Json response的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python在Windows8下獲取本機(jī)ip地址的方法
這篇文章主要介紹了python在Windows8下獲取本機(jī)ip地址的方法,涉及Python中socket包相關(guān)函數(shù)的使用技巧,需要的朋友可以參考下2015-03-03
Python matplotlib 繪制雙Y軸曲線圖的示例代碼
Matplotlib是非常強(qiáng)大的python畫圖工具,這篇文章主要介紹了Python matplotlib 繪制雙Y軸曲線圖,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
使用Python快樂(lè)學(xué)數(shù)學(xué)Github萬(wàn)星神器Manim簡(jiǎn)介
這篇文章主要介紹了使用Python快樂(lè)學(xué)數(shù)學(xué)Github萬(wàn)星神器Manim簡(jiǎn)介,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08
解決pytorch-yolov3 train 報(bào)錯(cuò)的問(wèn)題
今天小編就為大家分享一篇解決pytorch-yolov3 train 報(bào)錯(cuò)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02
python數(shù)據(jù)分析之DataFrame內(nèi)存優(yōu)化

