手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >jQuery实现form表单元素序列化为json对象的方法
jQuery实现form表单元素序列化为json对象的方法
摘要:本文实例讲述了jQuery实现form表单元素序列化为json对象的方法。分享给大家供大家参考,具体如下:这段代码序列化form表单元素为j...

本文实例讲述了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实现form表单元素序列化为json对象的方法1

希望本文所述对大家jQuery程序设计有所帮助。

【jQuery实现form表单元素序列化为json对象的方法】相关文章:

jQuery实现文本展开收缩特效

jQuery实现在列表的首行添加数据

jQuery实现dialog设置focus焦点的方法

JavaScript实现表格点击排序的方法

jQuery实现表格行上下移动和置顶效果

jQuery实现强制cookie过期方法汇总

JQuery自动触发事件的方法

js+cookies实现悬浮购物车的方法

jQuery实现html表格动态添加新行的方法

jQuery实现不断闪烁文字的方法

精品推荐
分类导航