Home > Web Front-end > JS Tutorial > body text

Ajax--form mapping

坏嘻嘻
Release: 2018-09-13 17:42:22
Original
1558 people have browsed it

The examples in this article describe python mapping lists. Share it with everyone for your reference. The specific analysis is as follows:

1 In mapping form serialization to background entity objects, many detours have been taken, which are summarized as follows.

Form:

<form  id="form01" enctype="multipart/form-data">
        <input type="text" name="name" id="name"/> 
        <input type="text" name="password" id="password"/>
        <input type="button" value="确认" onclick="upload()">
    </form>
Copy after login

JS method:

function upload() {
        $.ajax({
            type:"POST",
            url : &#39;<%=basePath%>upload01.do&#39;, //用于文件上传的服务器端请求地址
            data : formToJson($("#form01")),
            contentType: &#39;application/json; charset=utf-8&#39;,
            success : function(data, status) //服务器成功响应处理函数
            {
                alert(data);
            },
            error : function(data, status, e)//服务器响应失败处理函数
            {
                alert(e);
            }
        });
    }    //将表单数据转化为JSON数据 form为表单对象,如$("#form01"),返回序列化数据
    function formToJson(form) {
        var data = form.serialize();
        data = decodeURIComponent(data, true);//防止中文乱码  
        data = data.replace(/&/g, "&#39;,&#39;");
        data = data.replace(/=/g, "&#39;:&#39;");
        data = "({&#39;" + data + "&#39;})";
        obj = eval(data);
        obj=JSON.stringify(obj);        return obj;
    }
Copy after login

It should be noted that why not directly use serialize() to serialize the form? Still have this trouble. When I did it, $("#form").serialize() returned the form name=1&password=1. I don't know how jquery can serialize it like this. I searched online for a long time, but to no avail. I saw a blog. http://www.cnblogs.com/suruozhong/p/6256457.html, convert this strange serialization result into JSON form by changing characters, and then OK, thank you blogger.
Backend controller:

@RequestMapping(value = "upload01", method = RequestMethod.POST)    public void uploadText01(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestBody User user) {
        System.out.println("run in");
    }
Copy after login

It should be noted that @RequestBody is added in front of the object, so that the JSON data in the frontend will be mapped to the object, otherwise a series of errors will be reported:

Unsupported Media TypeContent type &#39;application/json;charset=UTF-8&#39; not supported
Copy after login

However, it is possible that your entity name does not match the name attribute value in the tag, causing this error.
The reason why the form cannot be mapped to the background entity may be due to the lack of shelf package.

<!-- JSON支持 -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <!--指定jdk版本 -->
            <classifier>jdk15</classifier>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
Copy after login

2 Submit the form directly in the method

<form id="form01" enctype="multipart/form-data">
        <input type="text" name="name" id="name" /> <input type="password"
            name="password" id="password" /> <input type="button"
            onclick="doConfirmForm()" value="确认">
    </form>
Copy after login
function doConfirmForm(){
        var form01=$("#form01");
        form01.submit();
    }
Copy after login

3 Convert the Form form to FormData and then submit it as JSON

<body>
    <form id="form">
            name:<br>
        <input type="text" name="name">
        <br>
         password:<br>
        <input type="text" name="password">
    </form> </body><script type="text/javascript" src="./jquery-1.10.2.js"></script><script type="text/javascript">

            var formData = new FormData($("#form")[0]);
            formData.append("createDate",new Date());

            $.ajax({
                type: "POST",
                data: convertFormDataToJson(formData),
                url: "http://localhost:80/test/requestBody",
                contentType: &#39;application/json; charset=utf-8&#39;,
                dataType: "json",
                success: function(result) {
                    console.log(result);
                }
            });            function convertFormDataToJson(formData) {
                var objData = {};                for (var entry of formData.entries()){
                    objData[entry[0]] = entry[1];
                }                return JSON.stringify(objData);
            }    </script>
Copy after login

Related recommendations:

JSP form submit submission mapping Servlet problem_html/css_WEB-ITnose

python mapping list example analysis

The above is the detailed content of Ajax--form mapping. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!