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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14026539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:28:29  来源:igfitidea点击:

Can I append an array to 'formdata' in javascript?

javascriptjqueryarraysmultipartform-data

提问by Don P

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 和附加数组的任何已知问题?

Instantiate formData:

实例化 formData:

formdata = new FormData();

formdata = new FormData();

The array I create. Console.log shows everything working fine.

我创建的数组。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);

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

回答by raina77ow

How about this?

这个怎么样?

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

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

...,相应地,json_decode在服务器上使用来解析它。看, FormData.append 的第二个值可以是...

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

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

The way I see it, your tagsarray contains objects (@Musa is right, btw; making this_tagan 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.

在我看来,您的tags数组包含对象(@Musa 是对的,顺便说一句;制作this_tag一个数组,然后为其分配字符串属性是没有意义的;改用普通对象),因此本机转换(使用toString())是不够的。不过,JSON'ing 应该可以获取信息。

As a sidenote, I'd rewrite the property assigning block just into this:

作为旁注,我将属性分配块重写为:

tags.push({article: article, gender: gender, brand: brand});

回答by Yosuke

Writing as

写作

var formData = new FormData;
var array = ['1', '2'];
for (var i = 0; i < array.length; i++) {
    formData.append('array_php_side[]', array[i]);
}

you can receive just as normal array post/get by php.

您可以像普通的数组 post/get 一样通过 php 接收。

回答by halfbit

use "xxx[]"as name of the field in formdata (you will get an array of - stringified objects - in you case)

使用"xxx[]"作为FORMDATA字段的名称(您将得到的数组-字符串化的对象-在你的情况下)

so within your loop

所以在你的循环中

$('.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);    
            formdata.append('tags[]', this_tag);
...

回答by Doglas

Function:

功能:

function appendArray(form_data, values, name){
    if(!values && name)
        form_data.append(name, '');
    else{
        if(typeof values == 'object'){
            for(key in values){
                if(typeof values[key] == 'object')
                    appendArray(form_data, values[key], name + '[' + key + ']');
                else
                    form_data.append(name + '[' + key + ']', values[key]);
            }
        }else
            form_data.append(name, values);
    }

    return form_data;
}

Use:

用:

var form = document.createElement('form');// or document.getElementById('my_form_id');
var formdata = new FormData(form);

appendArray(formdata, {
    'sefgusyg': {
        'sujyfgsujyfsg': 'srkisgfisfsgsrg'
    }, test1: 5, test2: 6, test3: 8, test4: 3, test5: [
        'sejyfgjy',
        'isdyfgusygf'
    ]
});

回答by Deva

var formData = new FormData;
var alphaArray = ['A', 'B', 'C','D','E'];
for (var i = 0; i < alphaArray.length; i++) {
    formData.append('listOfAlphabet', alphaArray [i]);
}

And In your request you will get array of alphabets.

并且在您的请求中,您将获得字母数组。

回答by llioor

This works for me when I sent file + text + array:

当我发送文件 + 文本 + 数组时,这对我有用:

const uploadData = new FormData();
if (isArray(value)) {
  const k = `${key}[]`;
  uploadData.append(k, value);
} else {
  uploadData.append(key, value);
}


const headers = {
  'Content-Type': 'multipart/form-data',
};

回答by Mobasher Fasihy

Simply you can do like this:

你可以这样做:

var formData = new FormData();
formData.append('array[key1]', this.array.key1);
formData.append('array[key2]', this.array.key2);

回答by Marko Rochevski

You can only stringify the array and append it. Sends the array as an actual Array even if it has only one item.

您只能将数组字符串化并附加它。将数组作为实际数组发送,即使它只有一项。

const array = [ 1, 2 ];
let formData = new FormData();
formData.append("numbers", JSON.stringify(array));