Home  >  Article  >  Web Front-end  >  Solve the problem of spring mvc returning json data to ajax and reporting error parseerror

Solve the problem of spring mvc returning json data to ajax and reporting error parseerror

亚连
亚连Original
2018-05-22 15:28:401662browse

Recently, when using ajax to receive json data from spring mvc, a parseerror error always occurs. Here, through this article, I will share with you the solution to the parseerror problem when spring mvc returns json data to ajax. Friends who need it can refer to it

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 yyGroupFunctionList) throws JsonProcessingException{ 
     
    return "success"; 
  }

Query the data and find the following answer:

When using simple types, that is : When using a type like 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.jar

Solution:

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 yyGroupFunctionList) throws JsonProcessingException{ 
     Map map = new HashMap(); 
     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"}

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Ajax cooperates with node js multer to implement the file upload function

##The principle of Ajax cross-domain request (Figure Text tutorial)

jQuery Validator verifies Ajax form submission method and Ajax parameter passing method (graphic tutorial)

The above is the detailed content of Solve the problem of spring mvc returning json data to ajax and reporting error parseerror. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn