我目前正在使用下面的 jquery ajax 方法通过 POST 请求提交数据,并且我在控制台中成功获得了返回结果(见下文),其中显示了提交到服务器的 JSON 请求。但是我无法弄清楚如何在 Django View 中解析 JSON 对象。我该如何编写 View ,以便可以解析 JSON 对象并获取“schedule_name”以在 Django View 中执行以下命令。请参阅下面我的观点的副本。
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
})
最佳答案
我通过对 Django 进行以下更改解决了该问题
Django view
data = json.loads(request.POST.get('json_items'))
name = data['nameOfSchedule']['schedule_name']
Schedule.objects.create(schedule_name = name)
关于javascript - 如何从 Ajax POST 解析 Django View 中的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39296014/