为什么当我尝试获取从 axios 发送的数据数组时,列表会分成多个值(views.py)

问题描述 投票:0回答:1

我尝试通过 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)>]}>

为什么会发生这种情况?如何将数据列表传递到后端并循环访问它?

谢谢你。

python reactjs django axios
1个回答
0
投票

JavaScript

Arrays
Objects
,因此即使您
console.log
它们,您也会得到一个
Object
,其中键作为
Array
元素索引,值作为实际
Array
元素。

要将其作为数组通过网络传递 [1] 最好的选择是使用

JSON.stringify
编码为 JSON。

details: JSON.stringify(details), <===== problem solved!

[1] 我所说的数组是指具有我们都认识的数组表示形式 [•••] 的数据。
© www.soinside.com 2019 - 2024. All rights reserved.