如何解决将 JavaScript 数组字符串化以发送到 PHP 脚本
我在 JavaScript 中有一个多维数组,我需要将它发送到 PHP 脚本。
下面是我目前正在做的发送数据但它发送的是空白数据。
我已将范围缩小到我在图像中登录的内容。
是否有其他方式发送此内容或为什么 JSON.stringify 显示为空白?
console.log(results);
console.log(JSON.stringify(results));
var form_data = new FormData();
form_data.append("results",JSON.stringify(results));
fetch('myfile.php',{
method: 'POST',body: form_data
})
编辑
var response_object = {"1": response1,"2": response2};
var test_object = {[current_test]: response_object};
var section_object = {[current_section]: test_object};
results = { ...results,...section_object }
解决方法
这是因为您没有向数组添加元素,而只是向其附加属性,例如 'section1'
和 'test1'
,您应该在某些对象上声明这些属性,然后将这些对象插入数组,请参阅在下面的示例中会发生什么以及如何避免这种情况:
let result = [];
// BAD
result['section1'] = [];
result['section1']['test1'] = [,"2","3"];
result['section1']['test2'] = [,"4","5"];
result['section2'] = [];
result['section2']['test1'] = [,"3"];
result['section2']['test2'] = [,"5"];
console.log('BAD',JSON.stringify(result));
// GOOD
result = [{
'section1': [
{'test1': [,"3"]},{'test2': [,"5"]}
]
},{
'section2': [
{'test1': [,"5"]}
]
}];
console.log('GOOD',JSON.stringify(result));
(代表问题作者发布答案,将其移至答案空间)。
最终工作代码:
var response_object = {"1": response1,"2": response2};
var test_object = {[current_test]: response_object};
if(results[current_section]){
var section_object = { ...results[current_section],...test_object};
results[current_section] = section_object;
}else{
var section_object = {[current_section]: test_object};
results = { ...results,...section_object};
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。