今天传数组参数,竟然不会用,记下来,加深印象。
1、页面ajax默认传参
function arrayParam(){ var contextPath = $('#contextPath').val(); var params = {}; params["names"] = ["张三", "李四", "王武"]; params["ages"] = [20, 26, 48]; var url = contextPath + "/array/getParamArray.do"; $.post(url, params, function(data){ alert(data); }); }
controller层
@RequestMapping(value="/getParamArray") public String getParamArray(@RequestParam("names[]") String[] names, @RequestParam("ages[]") int[] ages){ LOG.info("getParamArray names={}, ages={}", Arrays.toString(names), Arrays.toString(ages)); return "viewName"; }
2、ajax传数组参数,默认在参数名后面加[],这一点和表单传参不一样,如果想和表单传参一样,可以如下
function arrayParam2(){ var url = contextPath + "/array/getParamArray.do"; var params = {}; params["names"] = ["张三", "李四", "王武"]; params["ages"] = [20, 26, 48]; $.ajax({ url: url, type: 'post', traditional: true, // 和表单传数组参数一样。 data:params, success:function(data){ alert(data); } }); }
这时controller层的参数名字没有后面的[]括号了。
@RequestMapping(value="/getParamArray2") public String getParamArray2(@RequestParam("names") String[] names, @RequestParam("ages") int[] ages){ LOG.info("getParamArray names={}, ages={}", Arrays.toString(names), Arrays.toString(ages)); return "viewName"; }
3、表单传数组参数,参数名字可以很灵活,后面可加[],可不加,controller层的参数名字要对应起来
<form action="<%=contextPath %>/array/getParamArray2.do" method="post"> <table> <tr> <td>名字1</td><td><input name="names[]" value="张三" /></td> </tr> <tr> <td>名字2</td><td><input name="names[]" value="李四" /></td> </tr> <tr> <td>年龄1</td><td><input name="ages" value="30" /></td> </tr> <tr> <td>年龄2</td><td><input name="ages" value="25" /></td> </tr> <tr> <td><input type="reset" value="重置" /></td> <td><input type="submit" value="提交" /></td> </tr> </table> </form>
controller层的参数名字和form表单中的名字一致
@RequestMapping(value="/getParamArray3") public String getParamArray3(@RequestParam("names[]") String[] names, @RequestParam("ages") int[] ages){ LOG.info("getParamArray names={}, ages={}", Arrays.toString(names), Arrays.toString(ages)); return "viewName"; }