数组添加进formdata,我可以在javascript中将数组附加到'formdata'吗?

I'm using FormData to upload files. I also want to send an array of other data.

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.

Any known issues with FormData and appending arrays?

Instantiate formData:

formdata = new FormData();

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);

How I send it:

// 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();

}

});

解决方案

How about this?

formdata.append('tags', JSON.stringify(tags));

... and, correspondingly, using json_decode on server to deparse it. See, the second value of FormData.append can be...

a Blob, File, or a string, if neither, the value is converted to a

string

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});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值