ajax我們經常用到,傳的數據格式簡單粗暴,由於前端傳的數據格式又是json數據,json數據又有對象,數組。
後臺小GG稍不注意,抵擋不住前端MM攻擊,連敗....
女人,惹不起呀,但是要寵着,紳士嘛,hahahaha....,
特總結以下以備應對,此總結經過專業嚴刑拷打,
磨練而出,話說:不抵一萬,也低三千,開始看
1、以RequestParam接收
前端傳來的是json數據不多時:[id:id],可以直接用@RequestParam來獲取值
@RequestMapping(value = "/update")
@ResponseBody
public String updateAttr(@RequestParam ("id") int id) {
int res=xxService.deleteData(id);
return "success";
}
2、以實體類方式接收
前端傳來的是一個json對象時:{【id,name】},可以用實體類直接進行自動綁定
@RequestMapping(value = "/add")
@ResponseBody
public String addObj(@RequestBody Accomodation accomodation) {
this.xxService.insert(accomodation);
return "success";
}
3、以Map接收
前端傳來的是一個json對象時:{【id,name】},可以用Map來獲取
@RequestMapping(value = "/update")
@ResponseBody
public String updateAttr(@RequestBody Map<String, String> map) {
if(map.containsKey("id"){
Integer id = Integer.parseInt(map.get("id"));
}
if(map.containsKey("name"){
String objname = map.get("name").toString();
}
// 操作 ...
return "success";
}
4、以List接收
當前端傳來這樣一個json數組:[{id,name},{id,name},{id,name},...]時,用List<E>接收
@RequestMapping(value = "/update")
@ResponseBody
public String updateAttr(@RequestBody List<Accomodation> list) {
for(Accomodation accomodation:list){
System.out.println(accomodation.toString());
}
return "success";
}
5、以JSONobject形式接收
此接收匹配所有的類型,需要前後臺傳參數對應
@ResponseBody
@PostMapping("/info")
public JSONObject merchantForInfo(@RequestBody JSONObject jsonObject) {
Integer type = jsonObject.getInteger("type");
String bankname = jsonObject.getString("bankname");
String bankcard = jsonObject.getString("bankcard");
String idno = jsonObject.getString("idno");
}
6、接收json數組形式
形式1:
前臺傳數組:
var ids=[1,2,3,4,5,6]
$.ajax({
url:"http://localhost:8080/shanchu",
type:"post",
dateType:'json',
data:{
ids:ids
},
success:function(res){
var objs=eval(res); //解析json對象
//console.log("數據=="+JSON.stringify(objs));
console.log("數據=="+objs);
},
error:function(err){
alert("網絡連接失敗,稍後重試",err);
}
})
@RequestMapping("/shanchu")
public String shanchubyid(@RequestParam(value = "ids[]") String[] ids){
System.out.println("參數:ids:"+JSON.toJSONString(ids));
return "成功";
}
形式2:
@PostMapping("/xxx")
@ResponseBody
public Map<String, Object> xxx(@RequestParam(value = "ids[]") Integer[] ids,
@RequestParam String type) {
xxxx
return map;
}
var info = getIds();
$.ajax({
url: 'xxx',
type: 'POST',
dataType: "json",
async: false,
data: {
'type': 'type',
'ids': info
},
success: function (result) {
alert(result.message);
},
error: function (result) {
alert(result.message);
}
});