Jquery ajax access to those pits of SpringBoot Json

Let's talk about the problem of ajax access.

Let's look at the general situation first.

The backend is the environment built by springboot, and the controller is as follows:

@SuppressWarnings({ "rawtypes", "unchecked" })
    @PostMapping(value = "/tasklistbytask")
    private Object taskListbyList(@RequestBody Map reqMap) {
    	log.info("----------------tasklistbylist-----------------");
		……

At this time, the front end uses jquery's ajax method backend, always prompting the following error:

  WARN 3324 --- [nio-8082-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : 
Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]

The request source code is as follows:

$(function () {
  var theTemplateScript = $("#example-template").html();  
  var theTemplate = Handlebars.compile(theTemplateScript);  
	$.ajax({
		url : '/tasklistbytask', 
		type : 'post',
		async:false, 
		data : {pageNum:'1',pageSize:'20'},
		dataType : 'json',
		success: function(result){
			  var theCompiledHtml = theTemplate(result);  
			  $('#tbody').append(theCompiledHtml); 
		},
		fail:function(e){
	
		},
		error:function(e){
	
		}
});
})

Obviously, springboot believes that this request came through'application/x-www-form-urlencoded;charset=UTF-8, and this can also be seen through the packet capture tool.

 

At the same time, you can also see that because it is a post request, the parameters in json are submitted in the form of the request body.

Next, query the jquery document and found that this method is the default request method.

So, modify the request method:

$.ajax({
		url : '/tasklistbytask', 
		type : 'post',
		async:false, 
		data : {pageNum:'1',pageSize:'20'},
		contentType:'application/json',
		dataType : 'json',
		success: function(result){
			  var theCompiledHtml = theTemplate(result);  
			  $('#tbody').append(theCompiledHtml); 
		},
		fail:function(e){
	
		},
		error:function(e){
	
		}

At this time, I requested the background again, and an error was reported:

WARN 3324 --- [nio-8082-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : 
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'pageNum': was expecting ('true', 'false' or 'null'); 
nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'pageNum': was expecting ('true', 'false' or 'null')
 at [Source: (PushbackInputStream); line: 1, column: 9]]

At this point, look at the request intercepted by the interceptor.

You can see that the request has changed to json mode, but in fact the sent json has not been parsed.

Finally, modify the data content to

data: { "pageno": 1, "Pagesize": 20} "

Serious json style, the request is successful!

Guess you like

Origin blog.csdn.net/H517604180/article/details/88856948