1. 程式人生 > >純js實現的serialize函式,序列化表單資料

純js實現的serialize函式,序列化表單資料

jquery的serialize用起來很爽吧,可惜jquery用在移動端的話效率很低,因為專案原因需要用到此函式,所以自己寫了一個,程式碼有些冗餘請見諒

			function nodeEach(list){ //將NodeList轉換為Array
				var arr = new Array();
				for( var i = 0 ; list.length > i ; i++ ){
					var node = list[i]; 
					arr.push(node);
				}
				return arr;
			}
			
			function in_array(search,array){
			    for(var i in array){
			        if(array[i]==search){
			            return true;
			        }
			    }
			    return false;
			}
			
			function getJsonObjLength(jsonObj) {
				var Length = 0;
				for (var item in jsonObj) {
					Length++;
				}
				return Length;
			}
		
			function serialize(id){
				var formDom = document.getElementById(id);
				var valueList = [];//儲存待處理的值,結構為: name , value 
				var data = {};//返回結果的json陣列
				
				var type1List = new Array();
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='color']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='date']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='datetime']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='datetime-local']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='email']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='hidden']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='month']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='number']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='password']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='range']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='search']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='tel']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='text']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='time']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='url']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='week']") ) );
				type1List = type1List.concat( nodeEach( formDom.querySelectorAll("input[type='radio']:checked") ) );
				for( var i = 0 ; type1List.length > i ; i++ ){
					var dom = type1List[i];
					var name = dom.getAttribute("name");//鍵名
					var value = dom.value;//值
					valueList.push( { name: name, value: value} );
					
				}
				
				var type3List = formDom.querySelectorAll("input[type='checkbox']:checked");
				var existCheckbox = new Array();
				for( var i = 0 ; type3List.length > i ; i++ ){
					if( in_array( type3List[i].getAttribute("name"), existCheckbox ) )//判斷是否已處理
						continue;
					
					var dom = type3List[i];
					
					var name = dom.getAttribute("name");//鍵名
					var value = dom.value;//值
					
					var cache = { name: name, value: [] };
					
					var l = formDom.querySelectorAll("input[type='checkbox'][name='"+name+"']:checked");
					for( var j = 0 ; l.length > j ; j++ ){
						cache.value.push( l[j].value );
					}
					valueList.push( cache );
					
				}
				
				var type4List = formDom.querySelectorAll("select");
				for( var i = 0 ; type4List.length > i ; i++ ){
					var name = type4List[i].getAttribute("name");//鍵名
					var value = type4List[i].options[type4List[i].options.selectedIndex].getAttribute("value"); //值
					valueList.push( { name: name, value: value} );
					
				}
				
				for( var i = 0 ; valueList.length > i ; i++ ){
					var row = valueList[i];
					var name = row.name;
					if( !name ){
						continue;
					}
					var value = row.value?row.value:null;
					var kArr = name.split("[");//是否是陣列
					
					var cDatas = "data";
					for( var j = 0; j < kArr.length; j++ ){
						var cn = kArr[j].replace(/\]/g, "").trim();//去除右方括號
						if(cn){
							
							if( !isNaN(cn) ){
								cDatas += "[" + cn + "]";
							}else{
								cDatas += "." + cn;
							}
							if( eval(cDatas+" == null") ) {
								eval( cDatas + "= {};" );
							}
							
						}else{//追加
							cDatas += "["+ eval( "getJsonObjLength("+cDatas + ")" )+"]";
							eval( cDatas + " = {};" );
						}
					}
					
					eval( cDatas + " = value;" );
					
				}
				return data;
			}


作者:sinprog

技術在於交流、溝通,轉載請註明出處並保持作品的完整性。