标签:sharp [] 还需要 stc others 使用 object var error
假设有一个bean名叫TestPOJO。
1、使用ajax从前台传递一个对象数组/集合到后台。
前台ajax写法:
var testPOJO=new Array();
//这里组装testPOJO数组
$.ajax({
url:“testController/testPOJOs”,
data:JSON.stringify(testPOJO),
type:"post",
dataType:"json",
contentType:"application/json",
success:function (res) {
},
error:function(msg){
}
});
后台接收方法:
@RestController
@RequestMapping("testController ")
public class testController {
@RequestMapping("/testPOJOs")
//如果类的注解是@Controller,那么方法上面还需要加@ResponseBody,因为@ResTController=@Controller+@ResponseBody
public String testPOJOs (@RequestBody TestPOJO [] testPOJO) {
//操作
}
//或者下面这个
//@RequestMapping("/testPOJOs")
//public String testPOJOs (@RequestBody List<TestPOJO> testPOJO) {
//操作
//}
}
无论是几维数组,前后台保持一致就行了。
2、除了传递对象集合,还需要传递其他字段。
前台ajax写法:
var testPOJO=new Array();
//这里组装testPOJO数组
$.ajax({
url:“testController/testPOJOs”,
data:{
“strs”: JSON.stringify(testPOJO),
“others”,”…”
},
type:"post",
dataType:"json",
success:function (res) {
},
error:function(msg){
}
});
后台接收方法:
@RestController
@RequestMapping("testController ")
public class testController {
@RequestMapping("/testPOJOs")
public String testPOJOs (String strs,String others) {
//操作使用fastjson进行字符串对象转换
List<TestPOJO> list=new ArrayList<>();
JSONObject json =new JSONObject();
JSONArray jsonArray= JSONArray.parseArray(strs);
for(int i=0;i<jsonArray.size();i++){
JSONObject jsonResult = jsonArray.getJSONObject(i);
TestPOJO testPOJO=JSONObject.toJavaObject(jsonResult,TestPOJO.class);
list.add(testPOJO);
}
//其他操作
}
}
或者直接把others和testPOJO数组重新组合一个新数组var arr=[testPOJO,”others的内容”],“strs”: JSON.stringify(arr),只传递一个strs字段就可以,然后后台转换。
SpringMVC,SpringBoot使用ajax传递对象集合/数组到后台
标签:sharp [] 还需要 stc others 使用 object var error
原文地址:https://www.cnblogs.com/jinghun/p/10397089.html