【问题标题】:How to Parse JSON object in Django View from Ajax POST如何从 Ajax POST 解析 Django 视图中的 JSON 对象
【发布时间】: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


【解决方案1】:

我通过对我的 Django 进行以下更改解决了这个问题

Django view

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

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

【讨论】:

    【解决方案2】:

    您可以为此使用 JsonResponse:

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

    更多信息请见https://docs.djangoproject.com/el/1.10/ref/request-response/

    【讨论】:

    • 这不起作用。尝试从我的 JSON 对象访问“nameOfScedule”,我收到 500 错误。
    • 为什么要访问响应对象中的数据?可以贴一些代码吗?
    猜你喜欢
    • 1970-01-01
    • 2013-06-16
    • 2015-11-25
    • 1970-01-01
    • 2016-09-21
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多