我尝试通过 axios 从前端发送数据列表,并使用 django 在views.py 中接收它。
我发送的数据样式:
[{ nameDetail: "1", valueDetail: "3" }, { nameDetail: "2", valueDetail: "4" }]
这是我在将值传递给 axios 之前
console.log
:
Array(2) 0: {nameDetail: 'Size', valueDetail: '2oz'}, 1: {nameDetail: 'Color', valueDetail: 'White'}, length: 2, [[Prototype]]: Array(0)
使用 axios 请求:
const { data } = await axios.post(
`http://localhost:8000/api/products/product/add/`,
{
name: name,
brand: brand,
category: category,
description: description,
badge: badge,
price: price,
discount: discount,
countInStock: countInStock,
images: images,
details: details, <===== this is the data that i have a problem with
},
{
headers: {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${userLogin.token}`,
},
}
)
但是当我使用
views.py
在 print(request.data)
中获取它时,数据转换:
<QueryDict: {'name': ['Electronic'], 'brand': ['ez'], 'category': ['Juices'], 'description': ['azea'], 'badge': ['promos'], 'price': ['22'], 'discount': ['2'], 'countInStock': ['2'], 'details[0][nameDetail]': ['Size'], 'details[0][valueDetail]': ['2oz'], 'details[1][nameDetail]': ['Color'], 'details[1][valueDetail]': ['White'], 'images[]': [<InMemoryUploadedFile: S33ef534d442d4a1d82ce7f52821f391aX (1).webp (image/webp)>]}>
为什么会发生这种情况?如何将数据列表传递到后端并循环访问它?
谢谢你。
JavaScript
Arrays
是 Objects
,因此即使您 console.log
它们,您也会得到一个 Object
,其中键作为 Array
元素索引,值作为实际 Array
元素。
JSON.stringify
编码为 JSON。
details: JSON.stringify(details), <===== problem solved!