欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

jQuery實(shí)現(xiàn)form表單元素序列化為json對(duì)象的方法

 更新時(shí)間:2015年12月09日 11:45:36   作者:NW_KNIFE  
這篇文章主要介紹了jQuery實(shí)現(xiàn)form表單元素序列化為json對(duì)象的方法,涉及jQuery基于serializeArray方法實(shí)現(xiàn)表單序列化的相關(guān)技巧,需要的朋友可以參考下

本文實(shí)例講述了jQuery實(shí)現(xiàn)form表單元素序列化為json對(duì)象的方法。分享給大家供大家參考,具體如下:

這段代碼序列化form表單元素為json對(duì)象:

<!Doctype html>
 <html xmlns=http://www.w3.org/1999/xhtml>
 <head>
 <title>jQuery擴(kuò)展——form序列化到j(luò)son對(duì)象</title>
 <meta http-equiv=Content-Type content="text/html;charset=utf-8">
 <script type="text/javascript" src="jquery-1.10.2.js"></script>
</head>
<body>
<p id="results"><b>Results:</b> </p>
<form>
 <select name="aModel.single">
 <option>Single</option>
 <option selected>Single2</option>
 </select>
 <br/><br/>
 <select name="aModel.multiple" multiple="multiple">
 <option selected="selected">Multiple</option>
 <option>Multiple2</option>
 <option selected="selected">Multiple3</option>
 </select>
 <br/><br/>
 <input type="checkbox" name="aModel.check" value="check1"/> check1
 <input type="checkbox" name="aModel.check" value="check2" checked="checked"/> check2
 <br/><br/>
 <input type="radio" name="aModel.radio" value="radio1" checked="checked"/> radio1
 <input type="radio" name="aModel.radio" value="radio2"/> radio2
</form>
<script type="text/javascript">
 var fields = $("select, :radio").serializeArray();
 var o={};
 jQuery.each(fields, function(i, fields){
  if(o[this.name]){
   /*
   表單中可能有多個(gè)相同標(biāo)簽,比如有多個(gè)label,
   那么你在json對(duì)象o中插入第一個(gè)label后,還要繼續(xù)插入,
   那么這時(shí)候o[label]在o中就已經(jīng)存在,所以你要把o[label]做嵌套數(shù)組處理
   */
   //如果o[label]不是嵌套在數(shù)組中
   if(!o[this.name].push){
    o[this.name]=[o[this.name]];  // 將o[label]初始為嵌套數(shù)組,如o={a,[a,b,c]}
   }
   o[this.name].push(this.value || ''); // 將值插入o[label]
  }else{
   o[this.name]=this.value || '';  // 第一次在o中插入o[label]
  }
 });
 $("#results").append(JSON.stringify(o));
 console.log(o); //用FireBug輸出
</script>
</body>
</html>

結(jié)果如下圖所示:

希望本文所述對(duì)大家jQuery程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論