问题描述
我正在使用FormData上传文件。我还想发送一系列其他数据。
I'm using FormData to upload files. I also want to send an array of other data.
当我发送图像时,它工作正常。当我将一些文本附加到formdata时,它工作正常。当我尝试在下面附加'tags'数组时,其他一切正常但没有发送数组。
When I send just the image, it works fine. When I append some text to the formdata, it works fine. When I try to attach the 'tags' array below, everything else works fine but no array is sent.
FormData和附加数组的任何已知问题?
Any known issues with FormData and appending arrays?
实例化formData:
Instantiate formData:
formdata = new FormData();
我创建的数组。 Console.log显示一切正常。
The array I create. Console.log shows everything working fine.
// 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的第二个值可以是...
... and, correspondingly, using json_decode
on server to deparse it. See, the second value of FormData.append can be...
我看到它的方式,你的标签
数组包含对象(@Musa是对的,顺便说一句;使 this_tag
一个数组,然后为它指定字符串属性没有意义;改为使用普通对象),所以原生转换(使用 toString()
)是不够的。不过,JSON'ing应该可以获得信息。
The way I see it, your tags
array contains objects (@Musa is right, btw; making this_tag
an Array, then assigning string properties to it makes no sense; use plain object instead), so native conversion (with toString()
) won't be enough. JSON'ing should get the info through, though.
作为旁注,我会重写属性赋值块:
As a sidenote, I'd rewrite the property assigning block just into this:
tags.push({article: article, gender: gender, brand: brand});
这篇关于我可以在javascript中将数组附加到'formdata'吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!