欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

HTML表单数据转JSON

程序员文章站 2023-10-28 14:47:28
问题描述 后端使用如下方式接收前端传入参数: 由于使用了 @RequestBody 注解,所以,前端需要传递 JSON 数据。那么,如何将表单数据快速转换为 JSON 字符串呢? 定义如下通用方法: 以上方法会返回一个 Object,然后再通过 JSON.stringify(obj) 将 JSON ......

问题描述

  后端使用如下方式接收前端传入参数:

1 @postmapping(value = "/test", produces = mediatype.application_json_utf8_value)
2@responsebody
3 public map<string, object> test(@requestbody map<string, object> map) {
4     system.out.println(map);
5     return map;
6 }

  由于使用了 @requestbody 注解,所以,前端需要传递 json 数据。那么,如何将表单数据快速转换为 json 字符串呢?

定义如下通用方法:

 1 function serializeform(form){
 2     var obj = {};
 3     $.each(form.serializearray(),function(index){
 4         if(obj[this['name']]){
 5             obj[this['name']] = obj[this['name']] + ','+this['value'];
 6         } else {
 7             obj[this['name']] =this['value'];
 8         }
 9     });
10     return obj;
11 }

  以上方法会返回一个 object,然后再通过 json.stringify(obj) 将 json 对象转换为 json 字符串即可。

  调用 serializeform() 方法只需要传入 表单对象即可,如: serializeform($('form'));

<form action="" method="post" id="myform">
        username: <input type="text" name="username" /><br /> password: <input type="password" name="password" /><br />
        <input type="button" value="submit" id="btn" />
    </form>

    <script>
        $(function() {
            $('#btn').click(function () {

                var jsonobj = serializeform($("form"));

                var jsonstr = json.stringify(jsonobj);

                $.ajax({
                    type: 'post',
                    url: 'http://localhost:8083/test',
                    data: jsonstr,
                    headers: {
                        'content-type': 'application/json;charset=utf-8'
                    },
                    success: function (data) {
                        alert("success: " + data);
                    },
                    error: function (data) {
                        alert("error: " + data);
                    }
                });

                return false;
            });
        });

        function serializeform(form){
            var obj = {};
            $.each(form.serializearray(),function(index){
                if(obj[this['name']]){
                    obj[this['name']] = obj[this['name']] + ','+this['value'];
                } else {
                    obj[this['name']] =this['value'];
                }
            });
            return obj;
        }
    </script>