JS,如何在FormData中追加数组? [英] JS, how to append array in FormData?

查看:114
本文介绍了JS,如何在FormData中追加数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在js FormData中追加数组.

i hope append array in js FormData.

像这样

var fd = new FormData();
fd.append("key", new Array(["a","b","c"]));
console.log(fd.get("key"));

结果是

a,b,c

结果类型为字符串" ...

result type is 'String'...

我想解析java(JSONArray)中的"aa"数组.

i want to parse "aa" array in java(JSONArray).

请帮助我.

推荐答案

您需要先对数据进行字符串化:

You need to stringify your data first:

fd.append("key", JSON.stringify(["a","b","c"]));

然后,当您要检索数据时,将其解析回数组.可以使用 JSON.parse()手动完成此操作,或者,如果您使用的是Express,可以使用JSON/urlencoded body-parser中间件为您完成.

And then when you want to retrieve the data parse it back into an array. This can be done manually using JSON.parse(), or, if you're using express, can be done for you by using the JSON/urlencoded body-parser middleware.

说明:

使用 .append()时,作为第二个参数传递的数据将转换为字符串.如果是数组,则调用 .toString()方法,该方法通过逗号将数组中的元素连接起来

When you use .append(), the data passed as a second argument will be converted into a string. In the case of an array, the .toString() method gets called which joins the elements inside your array by a comma

a,b,c

这不好,因为它不能轻易地解析回数组中,特别是当您具有复杂的数组(例如对象数组或多维数组)时.

This isn't good as this cannot be parsed back into the array easily, especially when you have complex arrays such as an array of objects or a multi-dimensional array.

但是,正如 @Phil 指出的那样,您可以使用 JSON.stringify 在您的输入数组上.这样,您将提供一个JSON字符串,可以使用 JSON.parse()

However, as @Phil pointed out, you can manage this by using JSON.stringify on your input array. This way, you're providing a JSON string, which can easily be parsed back into data using JSON.parse()

"[\"a\",\"b\",\"c\"]" // <-- can be parsed into an array using JSON.parse()

请参见下面的工作示例:

See working example below:

var fd = new FormData();
fd.append("key", JSON.stringify(["a","b","c"]));

var str_arr = fd.get("key");
console.log(str_arr); // string format
console.log(JSON.parse(str_arr)); // array format

这篇关于JS,如何在FormData中追加数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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