我目前正在使用以下jquery ajax方法通过POST请求提交数据,并且我在我的控制台(见下文)中成功获得了返回结果,该结果显示了提交给服务器的JSON请求。但是,我无法弄清楚如何在我的Django视图中解析JSON对象。我该怎么写我的视图,这样我才能解析我的JSON对象并获得" schedule_name"在我的Django视图中执行以下命令。请在下面查看我的观点副本。
Schedule.objects.create(schedule_name = Schedule)
$.ajax({
type: "POST",
url: "{% url 'addSchedule' building_pk %}",
dataType: "json",
data: {"json_items" : JSON.stringify(Schedule_Info)},
success : function(data)
{
$('.todo-item').val(''); // remove the value from the input
console.log(data); // log the returned json to the console
console.log("success"); // another sanity check
alert("Sucess");
},

提交请求后在控制台中输出JSON
json-items: "{
"nameOfSchedule":{"schedule_name":"Schedule"},
"Rooms":[
{"room_rank":"1","room_name":"Room 101 "},
{"room_rank":"2","room_name":"Room 102 "},
{"room_rank":"3","room_name":"Room 103 "},
{"room_rank":"4","room_name":"Room 104 "}
],
"Users":[
{"user_name":"test1@yahoo.com"},
{"user_name":"test2@yahoo.com"}
]
}"

Django View
def addSchedule(request, building_id):
building_pk = building_id
b = Building.objects.get(pk=building_pk)
floor_query = b.floor_set.all()
master_query = floor_query.prefetch_related('room_set').all()
if request.is_ajax() and request.POST:
data = request.POST
### Input the schedule name in the datase by parsing the JSON object
return HttpResponse(json.dumps(data),content_type="application/json")
else:
return render(request, 'scheduler/addSchedule.html', {'building_pk' : building_pk,
'building_query': master_query
})
答案 0 :(得分:0)
您可以使用JsonResponse:
return JsonResponse({'this': "will be converted to json"});
有关详细信息,请参阅https://docs.djangoproject.com/el/1.10/ref/request-response/
答案 1 :(得分:0)
我通过对Django进行以下更改来解决问题
Django view
data = json.loads(request.POST.get('json_items'))
name = data['nameOfSchedule']['schedule_name']
Schedule.objects.create(schedule_name = name)