前端如何赋值数组以及空值处理
2.1 数组的赋值如下 results,如果是字符串数组加上单引号即可。
2.2有三种情况,ajax是不会提交给后台。
- 数组为空[]
- 数组为空字符串 ‘’
- 数组没定义
这里看到提交给后台的数据只有results。这点很重要,关系到你如何控制不传递给后台数据的赋值问题。
2.3 避免赋null或者不赋值
- method:
- method:null
上面两种情况会导致前后端语法报错,要避免
后台接收数组
@RequestParam要求定义的value必须存在,否则报错。而required = false 避免数组为空时后台报错。
我们只需要做null值判断即可
@PostMapping("/xxx")
@ResponseBody
public List<CusLastTrace> list(@RequestParam(value = "methods[]",required = false)Integer[] methods,
@RequestParam(value = "targets[]",required = false)Integer[] targets,
@RequestParam(value = "results[]",required = false)Integer[] results,
CusLastTrace cusLastTrace){
System.out.println(cusLastTrace.getId());
System.out.println(cusLastTrace.getBrokerId());
for(int i =0;i<methods.length;i++){
System.out.println(methods[i]);
}
if(null==targets){
}else{
for(int i =0;i<targets.length;i++){
System.out.println(targets[i]);
}
}
for(int i =0;i<results.length;i++){
System.out.println(results[i]);
}
}