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

查看:124
本文介绍了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()

参见下面的工作示例:

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天全站免登陆