使用ajax在spring中将java数组从jsp发送到controller

时间:2014-05-10 03:47:47

标签: java jquery ajax spring jsp

我有一个jsp页面,它在java中有一个double []数组和一个按钮,这是JSP的代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%

    double[] beta = {1.2,4.3,1.0};       

%>

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

    <button id="validate">Validate</button>


</body>
</html>

在验证按钮上单击我正在进行ajax调用,该调用正在向控制器发送请求:

$('#validate').click(function() {
$.ajax({
    url : 'controllerMethod'
    type : 'POST'
    data : ''
    success:function(data){

    }
});
});

如何发送带有ajax请求的beta数组,以便我可以使用控制器方法访问它。

@RequestMapping(value = "/controllerMethod", method = RequestMethod.POST)
@ResponseBody
 public String validateSymbol(WebRequest webRequest,Model model,HttpServletRequest request, HttpServletResponse response) {

    //beta;

 }

1 个答案:

答案 0 :(得分:0)

只需在ajax数据中传递数组即可。 我在这里data array

$('#validate').click(function() {
  var data = [ "hello", "world" ];
$.ajax({
  url : 'controllerMethod',
  type: "POST", 
  dataType: 'json',
  data: "data="+data,
  success:function(data){

}
});
});

使用控制器中的String[] data

获取字符串数组,即@Requestparam
@RequestMapping(value = "/controllerMethod", method = RequestMethod.POST)
@ResponseBody
 public String validateSymbol(WebRequest webRequest,Model model,HttpServletRequest request, HttpServletResponse response,@RequestParam String[] data) {

    //beta;
    //Here you will get your array in `data String array` which is passed from ajax call
 }