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


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

测试用例:

I have a bike I have a car

测试结果:

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

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