SpringMVC accepts json jquery parameters and sequence of the form

html code

<form id="myform">
    user:<input type="text" name="username"><br>
    age:<input type="text" name="age" ><br>
    爱好:<input type="checkbox" name="hobby" value="篮球"> 篮球
    <input type="checkbox" name="hobby" value="乒乓球"> 乒乓球
    <input type="checkbox" name="hobby" value="足球"> 足球
</form>

1. The conventional manner reception parameters, where the form of the key-value using serializing and separated by an ampersand

$('#formbtn').click(function () {
            var serialize = $("#myform").serialize();
            console.log(serialize);
            $.post("/jsonTest",serialize,function (data) {
                console.log(data);
            })
 	});

Forwarding serialized form 2.jquery json objects widget

(function($){
            $.fn.serializeJson=function(){
                var serializeObj={};
                var array=this.serializeArray();
                var str=this.serialize();
                $(array).each(function(){
                    if(serializeObj[this.name]){
                        if($.isArray(serializeObj[this.name])){
                            serializeObj[this.name].push(this.value);
                        }else{
                            serializeObj[this.name]=[serializeObj[this.name],this.value];
                        }
                    }else{
                        serializeObj[this.name]=this.value;
                    }
                });
                return serializeObj;
            };
        })(jQuery);

3. using a plug-serialized form

Here Insert Picture Description
Submit a form when the runtime array of complex types accepted parameters failure, reason, such a request in the request header of the first type of transmission does not support complex
Here Insert Picture Description

Ajax following modification request code, where the data is converted into json json string, in the background using the received receiving requestBody

$.ajax({
      type:"post",
       url:"/jsonTest",
       data:JSON.stringify(serialize),
       contentType:"application/json;charset=UTF-8",
       success:function (data) {
           alert(data);
       }
   });

Background code

@RequestMapping("/jsonTest")
    @ResponseBody
    public String jsonTest(@RequestBody User user){
        System.out.println("测试json"+user);
        return "result";
    }

Note the following uses json dependence

 <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.8</version>
 </dependency>
 <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.8</version>
 </dependency>
Published 47 original articles · won praise 6 · views 2194

Guess you like

Origin blog.csdn.net/weixin_44467251/article/details/102732250