首页 > 代码库 > Jquery 将表单序列化为Json对象

Jquery 将表单序列化为Json对象

使用下面代码时注意不要忘记引入jquery文件,以下代码可以复制到html文件中执行可看到效果,非常方便好用。附代码:

<!DOCTYPE html><html><head>    <title></title>    <script src="jquery-2.0.3.min.js"> </script></head><body><form id="myForm" action="#">    <input name="name"/>    <input name="age"/>    <select multiple="multiple" name="interest" size="2">        <option value ="interest1">interest1</option>        <option value ="interest2">interest2</option>        <option value="interest3">interest3</option>        <option value="interest4">interest4</option>    </select>    <input type="checkbox" name="vehicle" value="Bike" /> I have a bike    <input type="checkbox" name="vehicle" value="Car" /> I have a car    <input type="submit"/></form><script>    (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);    $(function(){        $("#myForm").bind("submit",function(e){            e.preventDefault();            console.log($(this).serializeJson());        });    });</script></body></html>