使用jQuery的.post提交,并期望得到多個數據,Python后臺要使用json格式。
不指定datatype為json,讓jquery自行判斷數據類型。(注:跨域名請求數據,則使用 jsonp字符串)
若post指定數據類型json,則python取post數據,我覺著麻煩。讓jquery智能判斷,python返回字典最方便。
一般使用字典,而不是列表來返回 JSON內容.
import jsonfrom django.http import HttpResponseresponse_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的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答