This time I will bring you how to handle errors when returning json data to ajax in spring mvc. What are the things to note when handling spring mvc when returning json data to ajax? What are the practical cases? Get up and take a look.
Recently, when using ajax to receive json data from spring mvc, a parseerror error always occurs. The error source code is as follows: Front end:$.ajax({ type: 'POST', url: "groupFunctionEdit", dataType: 'json', contentType: "application/json", data: JSON.stringify(functiondata), success: function(data){ alert('数据加载成功'+data.msg); }, error: function(xhr, type){ alert('数据加载失败'); console.log(type); }
@RequestMapping("/groupFunctionEdit") public @ResponseBody Object groupFunctionEdit(@RequestBody List<YyGroupFunction> yyGroupFunctionList) throws JsonProcessingException{ return "success"; }
Query the data and find the following answer:
When using a simple type such as String to receive data, there is no need to use the @RequestBody annotation. Here you need to use spring mvc to process the dependent jar package of json: jackson.databind.jarSolution:
No need to modify the front end, in the background Encapsulate the required data with map and convert it into String type:@RequestMapping("/groupFunctionEdit") public @ResponseBody Object groupFunctionEdit(@RequestBody List<YyGroupFunction> yyGroupFunctionList) throws JsonProcessingException{ Map<String,Object> map = new HashMap<String,Object>(); map.put("msg", "success"); ObjectMapper mapper = new ObjectMapper(); String msg = mapper.writeValueAsString(map); return msg; }
{"msg":"success"}
How to implement the three-level linkage menu bar of ajax
Detailed explanation of ajax data processing steps (with code )
The above is the detailed content of How to handle errors when returning json data to ajax in spring mvc. For more information, please follow other related articles on the PHP Chinese website!