python3.x - python django通過ajax向后端傳json怎么解析
問題描述
我的json內(nèi)容是這樣的:
{ 'type':'user', 'ifor':[{ 'id':001, 'name:'lison'},{ 'id':002, 'name':'wei'} ]}
在JS中我是使用jquery的ajax方法傳的,這樣寫的:
$.ajax('url',{ type:'post', data:{type:'user',ifor: [ {id:001,name:'lison' }, {id:002,name:'wei' }] }, success:function(){}})
我的是python3.6,django是1.11.1,在django中的views.py中該怎么接收呢?我網(wǎng)上查了好多,有的說json.loads(request.body),有說simplejson.loads(request.raw_post_data)的,但貌似都有問題,請問大神該怎么接收并解析呢
問題解答
回答1:前端ajax:
data = {};$.ajax({ type: 'post', url: 'url', dataType: 'json', data: JSON.stringify(data), success: function(result) { }});
后端取值:
import jsondata = json.loads(request.body)print data[’key’]回答2:
你首先得確定你傳給后端的內(nèi)容, 是什么樣的, 不能直接就是json.loads假設(shè)view對應(yīng)方法源碼如下
def test(req): print(req.POST) # 通過輸出看看前端傳過來的數(shù)據(jù)是什么 return HttpResponse(’test’)
只有符合’{'aa':'xxx'...}’這樣的json格式才能夠被json.loads識別并反序列化, 如果傳回來的結(jié)果不是這樣的json格式, 那么就要調(diào)整前端的ajax, 以便能夠構(gòu)造出這樣的數(shù)據(jù), 具體可以通過dataType: json或者通過字符串拼接的方法構(gòu)造都可以, 詳情可以自行谷歌: ajax傳遞json數(shù)據(jù)
相關(guān)文章:
1. docker - 各位電腦上有多少個容器啊?容器一多,自己都搞混了,咋辦呢?2. MySQL數(shù)據(jù)庫中文亂碼的原因3. macos - mac下docker如何設(shè)置代理4. docker不顯示端口映射呢?5. android studio總是在processes running好久6. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””7. java - 請問在main方法中寫成對象名.屬性()并賦值,與直接參參數(shù)賦值輸錯誤是什么原因?8. docker-compose 為何找不到配置文件?9. angular.js - 關(guān)于$apply()10. docker 17.03 怎么配置 registry mirror ?
