我有兴趣从views.py以JSON格式获取插入操作的结果。我想,我的结果还不错。我的观点如下:
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)
从JQUERY传递的记录成功添加到数据库中。我现在想要的是{12:1,13:2}形式的JSON结果。
我的火袋显示响应:
12:1
13:2
我不确定这是否是一个有效的JSON。如果我列出(添加),它会改为:
0: 12
1: 13
我不想要的。我现在遇到的问题我想通过退回的项目,但我收到不正确的结果。我基本上想要得到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){
}
});
答案 0 :(得分:1)
改变你的观点。
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)
和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){
}
});