首页 > 解决方案 > 将 Integer[] 列表从 ajax 发送到 Spring Controller

问题描述

我试图将一些数据从前端发送到 Spring 中的控制器。我能够恢复除 Integer [] objectIds 之外的所有数据。

这是我的 ajax 函数:

           var dataToSend = [{ objectIds: 111 }, { objectIds: 222 }];
           dataToSend = JSON.stringify({ 'objectIds': dataToSend });

           $.ajax({
               type:'POST',
               url:'/sendData',
               data:{'start':start, 'end':end, 'locale':locale, dataToSend},
               async:false,
               dataType: "json",
               success:function(data){}
           });

这是我的控制器功能:

    @PostMapping(path="/sendData")
public @ResponseBody String sendData(HttpServletResponse response, 
        @RequestParam(required=true, name="start") String start, 
        @RequestParam(required=true, name="end") String end,
        @RequestParam(required=true, name="locale") Locale locale,
        @RequestParam(required=false, name="objectIds") Integer[] objectIds) throws DocumentException, IOException {

    //some more code
}

知道为什么它不起作用吗?

标签: javascriptajaxspringpostmodel-view-controller

解决方案


问题在于您发送 JSON 的方式

案例 1:您如何发送

 var dataToSend = [{ objectIds: 111 }, { objectIds: 222 }];
dataToSend = JSON.stringify({ 'objectIds': dataToSend });

var mainJSOn = {
    'start': "start",
    'end': "end",
    'locale': "locale",
    dataToSend
  }
  console.log(JSON.stringify(mainJSOn));

输出:

   {"start":"start","end":"end","locale":"locale","dataToSend":"{\"objectIds\":[{\"objectIds\":111},{\"objectIds\":222}]}"}

案例 2:您应该如何实际发送

    var dataToSend1 = [{ objectIds: 111 }, { objectIds: 222 }];
    dataToSend1 = JSON.stringify(dataToSend1 );

    var mainJSOn1 = {
        'start': "start",
        'end': "end",
        'locale': "locale",
        'objectIds': dataToSend1
      }



  console.log(JSON.stringify(mainJSOn1));

输出:

{"start":"start","end":"end","locale":"locale","objectIds":"[{\"objectIds\":111},{\"objectIds\":222}]"}

查看两种情况的输出。

像案例 2 中所做的那样更改您的代码

工作小提琴


推荐阅读