gpt4 book ai didi

javascript - FormData 附加嵌套对象

转载 作者:搜寻专家 更新时间:2023-11-01 00:50:27 24 4
gpt4 key购买 nike

是否可以将嵌套对象附加到 FormData

let formData = new FormData();
let data = {
title: 'title',
text: 'text',
preview: {p_title:'p title', p_text: 'p text'}
};

$.each(data, function(key, value) {
formData.append(key, value);
});

服务器控制台 - console.log(req.body)

{
title: 'title',
text: 'text',
preview: '[object Object]'
}

如何获取 preview: {p_title:'p title', p_text: 'p text'} 的准确值?

最佳答案

let formData = new FormData();
let data = {
title: 'title',
text: 'text',
preview: {p_title:'p title', p_text: 'p text'}
};

for(let dataKey in data) {
if(dataKey === 'preview') {
// append nested object
for (let previewKey in data[dataKey]) {
formData.append(`preview[${previewKey}]`, data[dataKey][previewKey]);
}
}
else {
formData.append(dataKey, data[dataKey]);
}
}

控制台表单数据

for (let val of formData.entries()) {
console.log(val[0]+ ', ' + val[1]);
}

关于javascript - FormData 附加嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52566331/

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