JavaScript的隐藏的输入数组 [英] Javascript Hidden Input Array

查看:129
本文介绍了JavaScript的隐藏的输入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能有一个隐藏的输入字段的值作为一个数组,然后把它传递给Spring MVC的控制器?

Is it possible to have the value of a hidden input field as an array and then have it passed to the Spring MVC controller?

function foo(){
 var myArray = new Array();
 myArray[0] = "Hello";
 myArray[1] = "World!";
 document.getElementById("hiddenInp").value=myArray;
}

然后在控制器做一些像

And then in the controller do something like

@RequestMapping ...
public String test(HttpServletRequest request){
String[] myArray = request.getParameter("hiddenInp");
// Assuming that the name of the hidden input field is also hiddenInp
System.out.println(myArray[0] + myArray[1]);
...
}

怎么样,如果我有一个关联数组工作吗?当指数为字符串,而不是INT

How about if I am working with an associative array? Where the indices are string rather than int

推荐答案

您最好的选择是的字符串化的数组,然后分配给它。

Your best option would be to stringify the array and then assign it.

element.value = JSON.stringify( ["Hello", "World"] );

结果值将是随后可在服务器上解析,重建阵列的 JSON字符串。这种方法适用的对象,以及如果你想有类似的东西关联数组。

The resulting value will be a JSON string that can then be parsed on the server, recreating the array. This approach works for objects as well if you wish to have something resembling an associative array.

我要指出的是,虽然 JSON 今天跨浏览器相当不错的支持,老的浏览器可能不支持它。您可以填充工具的功能很容易的在这种情况下:

I should note that while JSON has fairly good support across browsers today, older browsers may not support it. You can polyfill the feature fairly easily in those cases:

这篇关于JavaScript的隐藏的输入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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