国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

jQuery實現form表單元素序列化為json對象的方法

2019-11-20 11:03:03
字體:
來源:轉載
供稿:網友

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

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

<!Doctype html> <html xmlns=http://www.w3.org/1999/xhtml> <head> <title>jQuery擴展――form序列化到json對象</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]){   /*   表單中可能有多個相同標簽,比如有多個label,   那么你在json對象o中插入第一個label后,還要繼續插入,   那么這時候o[label]在o中就已經存在,所以你要把o[label]做嵌套數組處理   */   //如果o[label]不是嵌套在數組中   if(!o[this.name].push){    o[this.name]=[o[this.name]];  // 將o[label]初始為嵌套數組,如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>

結果如下圖所示:

希望本文所述對大家jQuery程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 六盘水市| 淮阳县| 邵阳县| 龙泉市| 原阳县| 金坛市| 文登市| 泸西县| 南投市| 广德县| 景德镇市| 太康县| 平原县| 乡城县| 桐梓县| 正安县| 孝感市| 高清| 通道| 永吉县| 普宁市| 海兴县| 汤阴县| 读书| 九江县| 平武县| 武威市| 辽源市| 安泽县| 常山县| 阿城市| 新巴尔虎左旗| 和林格尔县| 遂昌县| 泽库县| 永嘉县| 平遥县| 莱西市| 平潭县| 青州市| 桃源县|