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

 

测试

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
    
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>
    
    <script type="text/javascript">
        
    
        $(function(){
            
            (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 submit(){
            
            var url = "${pageContext.request.contextPath}/test.do"
            var param = $("#userForm").serializeJson();
            
            $.post(
                url,param,function(msg){
                
            },"json");
            
        }
    
    </script>

</head>
<body>

    <form id="userForm">
    
        姓名:  <input type="text" name="name" /> <br>
        年龄: <input type="text" name="age" /> <br>
        
        <a href="#" onclick="submit();">提交</a>
    </form>

</body>
</html>

image

posted @ 2016-08-24 18:29  ✈✈✈  阅读(6290)  评论(0编辑  收藏  举报