繁体   English   中英

从Ajax发送Integer []列表到Spring Controller

[英]Send list of Integer[] from ajax to Spring Controller

我试图在Spring中将一些数据从前端发送到Controller。 我可以恢复除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){}
           });

这是我的Controller函数:

    @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
}

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

问题在于您发送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));

OUTPUT:

   {"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));

OUTPUT:

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

查看两种情况的输出。

像案例2一样更改代码

工作小提琴

您正在将错误的对象objectIds起来并将关键的objectIds埋入其中

尝试更改为

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM