jquery扩展方法-将表单数据转为json对象

扩展方法

需要 引入 jquery

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

使用

var jsonObj = $("#myform").serializeObject();
console.log( jsonObj )

例子

<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>


<form id="myform">
    登录名:<input type="text" name="username" value="李雷"><br>
    密码:<input type="text" name="password" value="123456"><br>
    性别:<input type="radio" name="sex" value="0" >女&nbsp;&nbsp;
    <input type="radio" name="sex" value="1" checked>男&nbsp;&nbsp;<br>
    爱好:<input type="checkbox" value="wzry" name="like">王者荣耀&nbsp;&nbsp;
    <input type="checkbox" value="cj" name="like" checked>吃鸡&nbsp;&nbsp;
    <input type="checkbox" value="douyin" name="like" checked>抖音&nbsp;&nbsp;<br>

    民族:
    <select name="minzu">
        <option value="-1" >--请选择--</option>
        <option value="1" >汉族</option>
        <option value="2" selected>满族</option>
        <option value="3" >蒙古族</option>
    </select> <br>
    描述:<textarea name="descrip"></textarea><br>
    <input type="button" value="注册" id="reg">
</form>

<script>
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$("#reg").click(function() {

    var jsonObj = $("#myform").serializeObject();
    console.log( jsonObj )
});

</script>

原文出处:https://malaoshi.top/show_1IX1uTzNvnOL.html