javascript - 如何从 Ajax POST 解析 Django View 中的 JSON 对象

标签 javascript jquery json ajax django

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

相关文章:

javascript - 修复 asp.net 中 div 的按钮

javascript - 使用扩展语法替换字典中的项目

javascript - Angular ControlValueAccessor 的默认值因内部原因而变脏

javascript - 字符串正则表达式 pattern.replace(/\{0\}/, "$0.00") 不起作用

jquery - HTML 表单单选按钮可通过 jquery 提交或隐藏

javascript - jquery.form 插件,ajaxSubmit 和收到 HTTP 302 时 Hook

json - 使用 actix_web 对部分结构进行 Serde 反序列化

json - clojure 从 json 响应中获取数据

json - 读取大 json 文件的第 n 个元素

javascript - 在 JQuery AJAX 发布之前暂停