我如何使用jQuery Ajax将数组传递给Spring控制器方法 [英] How do I pass an array to a Spring controller method with jquery ajax

查看:94
本文介绍了我如何使用jQuery Ajax将数组传递给Spring控制器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的ajax电话:

Here's my ajax call:

 $.ajax({
     type: 'GET',
     url: contextPath + '/test/location',
     data: {'objectValues': object.objectValues },
     datatype: 'json',
     success: function( data ) {
     var obj = jQuery.parseJSON( data );
     }
   });

它给了我这个URL:

http://localhost:8080/test/location?objectValues [] = 1234567890& objectValues [] = 0987654321

http://localhost:8080/test/location?objectValues[]=1234567890&objectValues[]=0987654321

我的Spring方法签名如下:

My Spring method signature looks like this:

@RequestMapping(value = "/location", method=RequestMethod.GET)
    public @ResponseBody String loadLocation(@RequestParam(value="objectValues", required=false) String[] objectValues)

为什么我的objectValues值总是为空?

Why do I keep getting null for the value of objectValues?

推荐答案

尝试将您的RequestParam批注值更改为此:

Try changing your RequestParam annotation value to this:

@RequestParam(value="objectValues[]", required=false)

如果这解决了问题,那是由于Spring和jQuery之间的参数命名不兼容所致,其中jQuery希望在方括号中插入以表明参数是数组(我认为PHP也喜欢这样),但是春天不在乎.要查看相反的结果,请尝试将ajax请求的数据"参数设置为以下字符串:'objectValues = 1234567890& objectValues = 0987654321'

If this solves the problem, then it is due to a parameter naming incompatibility between Spring and jQuery, where jQuery wants to put square brackets in to indicate that a parameter is an array (I think PHP likes this too), but where Spring doesn't care. To see the reverse try setting the "data" parameter of the ajax request to the string: 'objectValues=1234567890&objectValues=0987654321'

这篇关于我如何使用jQuery Ajax将数组传递给Spring控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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