javascript - 将 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
}
知道为什么它不起作用吗?
解决方案
问题在于您发送 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 中所做的那样更改您的代码
推荐阅读
- python - 如何在 SQLAlchemy UPDATE 调用中的函数中嵌入函数
- php - 如何使用mysql查询选择下线用户?
- c - 我如何在不使用循环的情况下编写此函数?(while,for) 我只能使用递归
- redis - Spring Data Redis - 生菜连接池设置
- python - 买卖股票的最佳时机 II (Leetcode 问题与解决方案) 怎么了?
- javascript - 道具不动态更新
- c++ - 将文本附加到文件
- python - 带条件的列表理解
- php - Laravel Sanctum auth:sanctum 中间件,带有 Angular SPA 未经身份验证的响应
- python - 命令(MRO):无法创建一致的方法解析Pyqt5(继承python文件)