Home >Web Front-end >JS Tutorial >How to handle errors when returning json data to ajax in spring mvc
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); }Backend Controller:
@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; }The data passed to the front end becomes:
{"msg":"success"}Then use jQuery to parse it without reporting an error. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:
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!