[英]Looping over JSONResponse() result from django in jquery
I am interested in getting the results of an insert operation from views.py in form a JSON. 我对从views.py以JSON形式获取插入操作的结果感兴趣。 I am getting the results alright, I think.
我认为我得到的结果还不错。 my view looks like this:
我的看法是这样的:
added={}
if request.method=='POST':
#Post method initiated.
try:
for id in allergies:
allergy=PatientAllergy(patient=patient,allergy_id=id,addedby=request.user)
allergy.save()
added[allergy.id]=id
except BaseException as e:
pass
return JsonResponse(added,safe=False)
The records, passed from JQUERY, added successfully to the database. 从JQUERY传递的记录已成功添加到数据库中。 What I want to get now is a JSON result in the form of {12:1, 13:2}.
我现在想要得到的是{12:1,13:2}形式的JSON结果。
My firebag shows the response as: 我的消防袋将响应显示为:
12:1
13:2
I am not sure if this a valid JSON or not. 我不确定这是否是有效的JSON。 If I do list(added), it gives instead:
如果我列出(添加),它将给出:
0: 12
1: 13
which I don't want. 我不要 The problem I am having now I want to go thru the returned items but I am getting incorrect results.
我现在遇到的问题是想通过退回的物品进行检查,但结果不正确。 I basically want to get 12:1, 13:2.
我基本上想得到12:1、13:2。
$.ajax({
type: "POST",
url: "/patient/addallergy/",
data: postForm,
dataType : "json",
cache: "false",
success: function (result) {
alert(result.length); //gives undefined, rendering the below line meaningless
if (result.length>0){
$.each(result,function(key,value){
alert(key);
alert(value);
});
}
},
fail: function (result){
}
});
change your views like this. 这样改变你的看法。
added_list=[]
if request.method=='POST':
#Post method initiated.
try:
for id in allergies:
added ={} allergy=PatientAllergy(patient=patient,allergy_id=id,addedby=request.user)
allergy.save()
added[allergy.id]=id
added_list.append(added)
except BaseException as e:
pass
return JsonResponse(added_list,safe=False)
and in jquery 并在jQuery中
$.ajax({
type: "POST",
url: "/patient/addallergy/",
data: postForm,
dataType : "json",
cache: "false",
success: function (result) {
alert(result.length); //gives undefined, rendering the below line meaningless
if (result.length>0){
alert(JSON.stringify(result))
$.each(result,function(index,value){
console.log(value);
});
result.forEach( function (eachObj){
for (var key in eachObj) {
alert(key);
alert(eachObj[key])
}
});
}
},
fail: function (result){
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.