我可以在javascript中将数组附加到'formdata'吗? [英] Can I append an array to 'formdata' in javascript?

查看:41
本文介绍了我可以在javascript中将数组附加到'formdata'吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 FormData 上传文件.我还想发送一组其他数据.

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

当我只发送图像时,它工作正常.当我将一些文本附加到 formdata 时,它工作正常.当我尝试附加下面的标签"数组时,其他一切正常,但没有发送数组.

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 = 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...

Blob、File 或字符串,如果两者都不是,则将值转换为字符串

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

在我看来,你的 tags 数组包含对象(@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'吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆