簡體   English   中英

如何從Ajax POST在Django View中解析JSON對象

[英]How to Parse JSON object in Django View from Ajax POST

我目前正在使用以下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

                                                          })

您可以為此使用JsonResponse:

return JsonResponse({'this': "will be converted to json"});

有關更多信息,請參見https://docs.djangoproject.com/el/1.10/ref/request-response/

我通過對Django進行以下更改解決了該問題

Django view

data = json.loads(request.POST.get('json_items'))

name = data['nameOfSchedule']['schedule_name']
Schedule.objects.create(schedule_name = name)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM