gpt4 book ai didi

javascript - jQuery 不会正确地发布包含数组作为其属性之一的 JSON

转载 作者:行者123 更新时间:2023-11-30 11:30:25 25 4
gpt4 key购买 nike

我正在尝试使用 jQuery 将一个 JSON 对象发送到我的 API 端点,该对象的属性之一是数组。我这样定义它:

let bidding = {
"name": $("#name").val(),
"applicant": $("#applicant").val(),
"start_date": $("#start_date").val(),
"end_date": $("#end_date").val(),
"products": []
}

$("#products").children(".dropdown").each(function(key, value) {
bidding.products.push(
{
"product_name": $(value).children(".btn").text(),
"quantity": $(value).children("input").val()
}
);
});

当我执行 console.log(JSON.stringfy(bidding)) 时,它会按预期进行解析,例如:

{
"name":"Material de Construção",
"applicant":"Prefeitura",
"start_date":"26/09/2017",
"end_date":"01/10/2017",
"products":[
{"product_name":"Cimento (5kg)","quantity":"200"},
{"product_name":"Tijolo","quantity":"100"},
{"product_name":"Caneta","quantity":"5"}
]
}

但是当我使用 $.post("/api", bidding); 发布它时,我的 API 会像这样接收它:

{
name: 'Material de Construção',
applicant: 'Prefeitura',
start_date: '26/09/2017',
end_date: '01/10/2017',
'products[0][product_name]': 'Cimento (5kg)',
'products[0][quantity]': '200',
'products[1][product_name]': 'Tijolo',
'products[1][quantity]': '100',
'products[2][product_name]': 'Caneta',
'products[2][quantity]': '5'
}

我怎样才能让 jQuery 停止为数组中的每个条目创建新属性,而是将整个数组作为单个属性发送?

最佳答案

需要设置为false:

processData: By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

因此您的帖子将是:

$.ajax({
type: "POST",
url: "/api",
data: JSON.stringify(bidding),
processData: false,
contentType: "application/json",
dataType:"json",
success: function () {
}
});

关于javascript - jQuery 不会正确地发布包含数组作为其属性之一的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46435526/

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