My darling, the background of the ajax pass value cannot be received

My darling, I can't receive it in the background using ajax to pass the value!

Situation: When using ajax to pass values, Ah Hong encountered the following situations. The ajax request method of setting jsp is as follows:

<script>
    $("#btn1").click(function (){
    
    
        let url = "${pageContext.request.contextPath}/user/getAjaxInfo";
        $.ajax({
    
    
            type:'post',
            dataType:'json',
            url:url,
            data:{
    
    
                "id":23,
                "username":"王五"
            },
            contentType:'application/json;charset=utf-8',
            success: function (resp) {
    
    
                alert(JSON.stringify(resp));
            }
        })
    })
</script>

Use springMVC to receive parameters:

  @ResponseBody
    @RequestMapping("/getAjaxInfo")
    public String ajax( @RequestParam("id") int id ,@RequestParam("username") String username){
    
    
        StringBuffer str = new StringBuffer();
        str.append(" id="+id).append("username="+username);
        System.out.println("------------"+str.toString());
        return str.toString();
    }

An error occurred in the background:

image-20220312112620676

Use a browser to view request information:

image-20220312112734943

Reason for the problem:

If this request is invalid, it means that the request has not entered the background server, that is, our value has not been passed to the background. I'm at a loss for words. I've tried it several times, but the problem still hasn't been solved.

problem analysis:

  1. Indicates that the data type received by the server is json
dataType:'json',
  1. Represents the data format of the data request server
contentType:'application/json;charset=utf-8',

contentType: "application/json", first make it clear that this is also a text type (same as text/json), representing a string in json format. If this type is set in ajax, the json object sent must use JSON .stringify can be serialized into a string to match the set type.

And I receive parameters in the background directly with @RequestParam to receive,

@RequestParam("id") int id ,@RequestParam("username") String username

What is passed is not a simple parameter, but a json object. So we must use @RequestBody to annotate to receive.

@RequestBody function : mainly used to parse the data in the json string passed from the front end to the back end

image-20220312115510544

But we want to get the corresponding value of each parameter. At this time, we can use Map<String,String> to receive

@RequestMapping(value = "/Login",method = {
    
    RequestMethod.POST})
     public @ResponseBody Boolean Login(@RequestBody Map<String,String> map) {
    
    
        //此时map.get("id" 23)就是前端的id
        System.out.println(map.get("id"));
       //map.get("username" wangwu)就是前端的username
       System.out.println(map.get( "username"));

Or use the default value of application/x-www-form-urlencoded (delete it from the foreground)

Background reception:

    @ResponseBody
    @RequestMapping("/getAjaxInfo")
    public String ajax( @RequestParam("id") int id ,@RequestParam("username") String username){
    
    
        StringBuffer str = new StringBuffer();
        str.append(" id="+id).append("username="+username);
        System.out.println("------------"+str.toString());
        return str.toString();
    }

image-20220312120120624

2. How to receive and parse two types of data, application/x-www-form-urlencoded and application/json?
Application/x-www-form-urlencoded This type of parameter submission method has two methods: get and post. The difference between the two methods is that the former puts the encoded parameters in the form of user=username&pass=password on the url. Submit, the latter is sent in the request body part of the request message, but the data is placed in a different location when sending data. After the server receives the parameters in the form of user=username&pass=password, the native servlet can obtain the parameters in the form of request.getParameter("user"), and the framework in spring mvc can automatically match the parameter names, that is When the name attribute of the form element is the same as the name of the received parameter, it can be automatically matched. If it is not the same, you can also use @RequestParam to match.

The native Servlet of application/json string data can use request.getParameterMap() to get it, but it should be noted that this method can only get the data passed in by Get method. The incoming post needs to be read using the input stream. In spring mvc, use @RequestBody to parse and bind json string parameters to method parameters.

Guess you like

Origin blog.csdn.net/qq_41239465/article/details/123441423