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

