前台json格式的数据如何传入后台
1. 将要传入后台的数据组装成JSON格式的字符串:
var jsonStr = [{'name':'jim' , 'age':20} , {'name':'king' , 'age':26},{'name':'jge' , 'age':30}]
2. 使用jQuery的ajax请求后台
jQuery.ajax({
type: "post",
url: url,
dataType : 'json',
data : {'mydata':jsonStr},
success: function(data,textStatus){
alert("操作成功");
},
error: function(xhr,status,errMsg){
alert("操作失败!");
}
});
3.后台数据的接收与解析:
String jsonStr = ServletActionContext.getRequest().getParameter("mydata");
JSONArray jsonArray = JSONArray.fromObject(jsonStr);
for(int i=0;i<jsonArray.length(); i++){
JSONObject jsonJ = jsonArray.getJSONObject(i);
jsonJ.getInt("name");
jsonJ.getString("age");
}
4. 操作完成
如果不行请参考:
@ApiOperation(value = "添加做题记录") @PostMapping("postAnswerLog") public JSONObject postAnswerLog(@ApiIgnore @RequestAttribute(required = false) Integer userId, @ApiParam("试卷")@RequestParam Integer examinationPaperId, @ApiParam("题库")@RequestParam String outlines ) { int flage = studentWordListService.postAnswerLog(userId,examinationPaperId,outlines); JSONObject json = new JSONObject(); if(flage>0){ json.put("state",200); json.put("msg", "成功"); }else{ json.put("state",400); json.put("msg", "失败"); } return json; }
//添加做题记录 @Override public int postAnswerLog(Integer userId, Integer examinationPaperId, String outlines) { userId = 1; EducationAnswerLog educationAnswerLog = new EducationAnswerLog(); educationAnswerLog.setStudentUseId(userId); educationAnswerLog.setExaminationPaperId(examinationPaperId); JSONArray jsonArray = JSONArray.fromObject(outlines); for(int i=0;i<jsonArray.size(); i++){ JSONObject jsonJ = jsonArray.getJSONObject(i); educationAnswerLog.setOutlineId(jsonJ.getInt("outlineId")); educationAnswerLog.setAnswerDetails(jsonJ.getString("answerDetails")); try { educationAnswerLogMapper.insert(educationAnswerLog); }catch (Exception e) { return 0; } } return 1; }