我正在构建一些表单数据,用数组填充它,并通过POST发送它,通过:
let fd = new FormData();
for (section in this.data.choices) {
let key = section+(this.data.choices[section] instanceof Array ? '[]' : '');
fd.append(key, this.data.choices[section]);
}
fetch('?get=plan', {method: 'post', body: fd}) //...
下面是this.data.choices
的结构
{
"mode": "o7ew4xqybwt",
"packages": [
"wx2xv1cakbe"
],
"usertypes": [
"s"
],
"subjects": [
"bxn5g1igm4l",
"u1osgpv37fl",
"q2scwqb27k7",
"fl9riri0wpr"
]
}
然而,在接收端,在PHP中,数组是扁平化的。print_r($_POST)提供:
Array
(
[mode] => o7ew4xqybwt
[packages] => Array
(
[0] => wx2xv1cakbe
)
[usertypes] => Array
(
[0] => s
)
[subjects] => Array
(
[0] => bxn5g1igm4l,u1osgpv37fl,q2scwqb27k7,fl9riri0wpr
)
)
毫无疑问,我遗漏了一些简单的东西,但任何帮助都将不胜感激。
发布于 2020-08-19 22:35:32
我认为您应该将数据作为JSON发送。它省去了很多麻烦,并避免了你引入的这种结构转换错误。相反,您可以将JS对象直接字符串化为JSON,然后将其发送到服务器。
然后在PHP端,您可以接收和解码它,然后像使用常规对象一样使用它(有关如何在PHP中正确地从POST请求接收JSON的指导,请参阅Receive JSON POST with PHP )。
发布于 2020-08-19 22:36:41
fd.append(key, this.data.choices[section]);
上行表示将单个值添加到键中,而不考虑[]
或normal键。您必须遍历它们,以将它们逐个添加为数组值。
let fd = new FormData();
for (section in this.data.choices) {
if(this.data.choices[section] instanceof Array){
this.data.choices[section].forEach(value => fd.append(section + '[]', value));
}else{
fd.append(section, this.data.choices[section]);
}
}
fetch('?get=plan', {method: 'post', body: fd}) //
另一种方法是,使用标头Content-type:application/json
按原样发送JSON。
https://stackoverflow.com/questions/63489153
复制相似问题