【问题标题】:How to accept JavaScript Array parameter in Spring MVC Controller in a jQuery ajax call?如何在 jQuery ajax 调用中接受 Spring MVC 控制器中的 JavaScript 数组参数?
【发布时间】:2013-01-29 02:20:58
【问题描述】:

我有一个这样的 jQuery ajax 调用:

var arr = ["a", "b", "c"];
$.get("/test", {testArray: arr}, function(data) {
    alert(data);
});

服务器端:

@RequestMapping(value = "/test", method = RequestMethod.GET)
public String addAnotherAppointment(
        HttpServletRequest request,
        HttpServletResponse response,
                    @RequestParam("arr") arr,
        Model model,
        BindingResult errors) {
}

那么如何接收参数呢?

谢谢。

【问题讨论】:

    标签: java spring jquery spring-mvc


    【解决方案1】:

    如果你使用spring 3.0++,使用“@ResponseBody”注解。

    你想发送一个 json 请求,并接收来自 json 的响应吗? 如果是这样,您将像这样更改您的代码。

    var list = {testArray:["a", "b", "c"]};
    $.ajax({
        url : '/test',
        data : $.toJSON(list),
        type : 'POST', //<== not 'GET',
        contentType : "application/json; charset=utf-8",
        dataType : 'json',
        error : function() {
            console.log("error");
        },
        success : function(arr) {
            console.log(arr.testArray);
            var testArray = arr.testArray;
             $.each(function(i,e) {
                 document.writeln(e);
             });
        }
      });
    

    服务器端:

    1. 创建您自己的“Arr”类。

      public class Arr {
       private List<String> testArray;
       public void setTestArray(List<String> testArray) {
           this.testArray = testArray;
       }
       public List<String> getTestArray() {
           return testArray;
       }
       }
      

      @RequestMapping(value = "/test", method = RequestMethod.POST)
      @ResponseBody// <== this annotation will bind Arr class and convert to json response.
         public Arr addAnotherAppointment(
         HttpServletRequest request,
          HttpServletResponse response,
          @RequestBody Arr arr, 
          Model model,
          BindingResult errors) {
              return arr;
      }
      

    【讨论】:

    【解决方案2】:

    @RequestParam("arr") arr, 更改为@RequestParam("testArray") String[] arr

    还将您的 HTTP 方法从 get 更改为 post

    请注意 @RequestParam 值必须与从 jquery ajax 发送的参数名称匹配。在您的情况下,参数名称是 testArray 并且值是 arr

    【讨论】:

      猜你喜欢
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      • 2018-02-24
      • 2013-02-16
      • 2015-07-15
      • 1970-01-01
      • 2012-03-19
      相关资源
      最近更新 更多