我正在使用 FormData 上传文件。我还想发送一系列其他数据。
当我只发送图像时,效果很好。当我将一些文本附加到表单数据时,它工作正常。当我尝试附加下面的“标签”数组时,其他一切正常,但没有发送数组。
FormData 和附加数组有任何已知问题吗?
实例化表单数据:
formdata = new FormData();
我创建的数组。 Console.log 显示一切正常。
// Get the tags
tags = new Array();
$('.tag-form').each(function(i){
article = $(this).find('input[name="article"]').val();
gender = $(this).find('input[name="gender"]').val();
brand = $(this).find('input[name="brand"]').val();
this_tag = new Array();
this_tag.article = article;
this_tag.gender = gender;
this_tag.brand = brand;
tags.push(this_tag);
console.log('This is tags array: ');
console.log(tags);
});
formdata.append('tags', tags);
console.log('This is formdata: ');
console.log(formdata);
如何发送:
// Send to server
$.ajax({
url: "../../build/ajaxes/upload-photo.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
$.fancybox.close();
}
});
最佳答案
这个怎么样?
formdata.append('tags', JSON.stringify(tags));
...,相应地,在服务器上使用 json_decode
来解析它。看,FormData.append 的第二个值可以是...
a Blob, File, or a string, if neither, the value is converted to a string
在我看来,你的 tags
数组包含对象(@Musa 是对的,顺便说一句;使 this_tag
成为一个数组,然后为其分配字符串属性是没有意义的; 使用普通对象代替),因此 native 转换(使用 toString()
)是不够的。不过,JSON 应该可以获取信息。
作为旁注,我将属性分配 block 重写为:
tags.push({article: article, gender: gender, brand: brand});
关于javascript - 我可以在 javascript 中将数组附加到 'formdata' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14026539/