jquery将表单数据转化为json对象的插件

今天在网上看到这个方法,感觉很不错,特意分享:


(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);


用法:

$("#myForm").bind("submit",function(e){
        e.preventDefault();
        console.log($(this).serializeJson());
    });

测试用例:

<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>

测试结果:

{age: "aa",interest: ["interest2", "interest4"],name: "dd",vehicle:["Bike","Car"]}

原文链接:http://my249645546.iteye.com/blog/1617872

你可能感兴趣的:(jquery,json对象,序列化表单数据)