【发布时间】:2017-01-10 18:47:59
【问题描述】:
我目前正在使用下面的 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
})
【问题讨论】:
标签: javascript jquery json ajax django