使用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 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 會導(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); }}使用.號來進(jìn)行得對應(yīng)Key值。
前端和后端都指定utf-8編碼,python返回中文,直接 {'status':'成功'},連u前綴都不用。
以上這篇使用Django和Python創(chuàng)建Json response的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點
疑難解答
圖片精選