本文實例講述了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程序設計有所幫助。
新聞熱點
疑難解答