gpt4 book ai didi

javascript - 在 Django 中将 JSONified 对象传递到后端?

转载 作者:行者123 更新时间:2023-12-01 01:31:31 26 4
gpt4 key购买 nike

我试图将 js 创建的对象转换为 JSON,然后传递到 Django 后端。

首先我列出了一个列表:

function get_account_info(){
var account_list = [];
$('.card').each(function(e){
var account = [];
account.push($(this).find('.name').val());
account.push($(this).find('.username').val());
account.push($(this).find('.password').val());

if(account[0] != null){
account_list.push(account);
}
})
return account_list;
}

然后我尝试发布它:

var account_info_json = JSON.parse(get_account_info());
$.ajax({
type:'POST',
url:'/create_new_group/create_group/',
data:{
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
account_info: account_info_json,
} ,
success:function(data){
if(data.status == 1){
//success!
console.log('Success!')
}
else if(data.status == 2){
//failed
console.log('Failed!')
}
}

这就是我在views.py中打印(json.dumps(request.POST))时得到的结果

{"csrfmiddlewaretoken": "token_data_is_here", "account_info": "[[\"1111111\",\"1111111\",\"1111111\"],[\"222222\",\"222222\",\"222222\"]]"}

我只能像搅拌一样访问这些数据,而不能访问 JSON。我怎样才能像 JSON 一样访问它?

最佳答案

所有的数据在发送之前都会被转换为字符串,所以当涉及到django时需要先将字符串转换为json。

从字符串转换为 json:

import json
str = json.loads(json_data)

从字符串中获取json:

import json
json_data = json.loads(str)

在你的情况下,你需要先将字符串转换为 json,然后才能在 python 中将其作为字典访问

希望对你有帮助!!

关于javascript - 在 Django 中将 JSONified 对象传递到后端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53237620/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com