Django индексное значение массива
Я отправляю массив массивов пост-запросом через $ajax
т.е:
[[1, "25, 25, 25", "pounds", "exercise note 1"],[2, "", "No Weight", "note 2"]]
Мой ajax:
$.ajax({
type: 'POST',
url: '',
dataType: 'json',
data:{
csrfmiddlewaretoken: csrftoken,
targets:JSON.stringify(targets),
// notes:notes,
// time:time,
// rating:rating
},
success: (res)=>{
console.log(res)
},
error: (error)=>{
console.log(error)
}
})
В django, когда я print(request.POST)
, я получаю
'targets[0][]':[1, "25, 25, 25", "pounds", "exercise note 1"], 'target[1][0]':[2, "", "No Weight", "note 2"]
.
Я пытался
JSON.stringify([[1, "25, 25, 25", "pounds", "exercise note 1"],[2, "", "No Weight", "note 2"]])
и я возвращаюсь
'targets': ['[[2,"25, 25, 25","Pounds","note 1"],[1,"","NoWeights","note 2"]]']
,
Я также пробовал:
ts.push(t)
django возвращает:
'targets[]': ['[2,"25, 25, 25","Pounds","note 1"]', '[1,"","NoWeights","note 2"]
чего я и хочу. Но когда я делаю
targets = request.POST.getlist('targets[])
for target in targets:
print(target[2]) -->I want either "25, 25, 25" or , ""
Но все, что я получаю, это , а когда я print(len(target))
первый массив возвращает 34. Почему? Как мне получить строки? Что я делаю неправильно? Я хочу присвоить каждый индекс в целевом массиве переменной, чтобы сохранить в базе данных
Если вы отправляете цели как JSON в вашем запросе (ПРИМЕЧАНИЕ: только часть целей является JSON), то вам придется декодировать его, когда вы получите его на стороне сервера.
targets = [[1, "25, 25, 25", "pounds", "exercise note 1"],[2, "", "No Weight", "note 2"]];
$.ajax({
type: 'POST',
url: '',
dataType: 'json',
data:{
csrfmiddlewaretoken: csrftoken,
targets:JSON.stringify(targets),
// notes:notes,
// time:time,
// rating:rating
},
success: (res)=>{
console.log(res)
},
error: (error)=>{
console.log(error)
}
}
});
targets_json = request.POST.get('targets')
targets = json.loads(targets_json)
for target in targets:
print(target[2])