码迷,mamicode.com
首页 > Web开发 > 详细

jQuery 将表单序列化为Json对象

时间:2016-08-24 19:00:45      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

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

技术分享

jQuery 将表单序列化为Json对象

标签:

原文地址:http://www.cnblogs.com/yangang2013/p/5804199.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!