詳談表單格式化插件jquery.serializeJSON
前言
前端在處理含有大量數(shù)據(jù)提交的表單時,除了使用Form直接提交刷新頁面之外,經(jīng)常碰到的需求是收集表單信息成數(shù)據(jù)對象,Ajax提交。
而在處理復(fù)雜的表單時,需要一個一個區(qū)手動判斷處理字段值,顯得非常麻煩。接下來介紹的插件將解決這個問題。
關(guān)于serializeJSON
使用jquery.serializeJSON,可以在基于jQuery或者Zepto的頁面中,調(diào)用 .serializeJSON() 方法來序列化form表單的數(shù)據(jù)成JS對象。
使用
只需要在jQuery或者Zepto時候引入即可
<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery.serializejson.js"></script>
示例
HTML form(支持input、textarea、select等標(biāo)簽)
<form id="my-profile"> <!-- simple attribute --> <input type="text" name="fullName" value="Mario Izquierdo" /> <!-- nested attributes --> <input type="text" name="address[city]" value="San Francisco" /> <input type="text" name="address[state][name]" value="California" /> <input type="text" name="address[state][abbr]" value="CA" /> <!-- array --> <input type="text" name="jobbies[]" value="code" /> <input type="text" name="jobbies[]" value="climbing" /> <!-- textareas, checkboxes ... --> <textarea name="projects[0][name]">serializeJSON</textarea> <textarea name="projects[0][language]">javascript</textarea> <input type="hidden" name="projects[0][popular]" value="0" /> <input type="checkbox" name="projects[0][popular]" value="1" checked /> <textarea name="projects[1][name]">tinytest.js</textarea> <textarea name="projects[1][language]">javascript</textarea> <input type="hidden" name="projects[1][popular]" value="0" /> <input type="checkbox" name="projects[1][popular]" value="1"/> <!-- select --> <select name="selectOne"> <option value="paper">Paper</option> <option value="rock" selected>Rock</option> <option value="scissors">Scissors</option> </select> <!-- select multiple options, just name it as an array[] --> <select multiple name="selectMultiple[]"> <option value="red" selected>Red</option> <option value="blue" selected>Blue</option> <option value="yellow">Yellow</option> </select> </form>
javascript:
$('#my-profile').serializeJSON(); // returns => { fullName: "Mario Izquierdo", address: { city: "San Francisco", state: { name: "California", abbr: "CA" } }, jobbies: ["code", "climbing"], projects: { '0': { name: "serializeJSON", language: "javascript", popular: "1" }, '1': { name: "tinytest.js", language: "javascript", popular: "0" } }, selectOne: "rock", selectMultiple: ["red", "blue"] }
serializeJSON方法返回一個JS對象,并非JSON字符串??梢允褂?JSON.stringify 轉(zhuǎn)換成字符串(注意IE8兼容性)。
JavaScript權(quán)威指南(第6版)(中文版) http://www.gooln.com/document/452.html
var jsonString = JSON.stringify(obj);
指定數(shù)據(jù)類型
獲取到的屬性值一般是字符串,可以通過HTML指定類型 : type 進(jìn)行強(qiáng)制轉(zhuǎn)換。
<form> <input type="text" name="notype" value="default type is :string"/> <input type="text" name="string:string" value=":string type overrides parsing options"/> <input type="text" name="excluded:skip" value="Use :skip to not include this field in the result"/> <input type="text" name="number[1]:number" value="1"/> <input type="text" name="number[1.1]:number" value="1.1"/> <input type="text" name="number[other stuff]:number" value="other stuff"/> <input type="text" name="boolean[true]:boolean" value="true"/> <input type="text" name="boolean[false]:boolean" value="false"/> <input type="text" name="boolean[0]:boolean" value="0"/> <input type="text" name="null[null]:null" value="null"/> <input type="text" name="null[other stuff]:null" value="other stuff"/> <input type="text" name="auto[string]:auto" value="text with stuff"/> <input type="text" name="auto[0]:auto" value="0"/> <input type="text" name="auto[1]:auto" value="1"/> <input type="text" name="auto[true]:auto" value="true"/> <input type="text" name="auto[false]:auto" value="false"/> <input type="text" name="auto[null]:auto" value="null"/> <input type="text" name="auto[list]:auto" value="[1, 2, 3]"/> <input type="text" name="array[empty]:array" value="[]"/> <input type="text" name="array[list]:array" value="[1, 2, 3]"/> <input type="text" name="object[empty]:object" value="{}"/> <input type="text" name="object[dict]:object" value='{"my": "stuff"}'/> </form>
$('form').serializeJSON(); // returns => { "notype": "default type is :string", "string": ":string type overrides parsing options", // :skip type removes the field from the output "number": { "1": 1, "1.1": 1.1, "other stuff": NaN, // <-- Other stuff parses as NaN (Not a Number) }, "boolean": { "true": true, "false": false, "0": false, // <-- "false", "null", "undefined", "", "0" parse as false }, "null": { "null": null, // <-- "false", "null", "undefined", "", "0" parse as null "other stuff": "other stuff" }, "auto": { // works as the parseAll option "string": "text with stuff", "0": 0, // <-- parsed as number "1": 1, // <-- parsed as number "true": true, // <-- parsed as boolean "false": false, // <-- parsed as boolean "null": null, // <-- parsed as null "list": "[1, 2, 3]" // <-- array and object types are not auto-parsed }, "array": { // <-- works using JSON.parse "empty": [], "not empty": [1,2,3] }, "object": { // <-- works using JSON.parse "empty": {}, "not empty": {"my": "stuff"} } }
數(shù)據(jù)類型也可以指定在 data-value-type 屬性中,代替 :type 標(biāo)記。
<form> <input type="text" name="number[1]" data-value-type="number" value="1"/> <input type="text" name="number[1.1]" data-value-type="number" value="1.1"/> <input type="text" name="boolean[true]" data-value-type="boolean" value="true"/> <input type="text" name="null[null]" data-value-type="null" value="null"/> <input type="text" name="auto[string]" data-value-type="auto" value="0"/> </form>
options配置
默認(rèn)配置
Values始終為字符串(除非在input names使用:types )
Keys始終為字符串(默認(rèn)不自動檢測是否需要轉(zhuǎn)換為數(shù)組)
未選擇的checkboxes會被忽略
disabled的elements會被忽略
自定義配置
包含未勾選的checkboxes
serializeJSON 支持 checkboxUncheckedValue 配置,或者可以在checkboxes添加 data-unchecked-value 屬性。
默認(rèn)方法:
<form> <input type="checkbox" name="check1" value="true" checked/> <input type="checkbox" name="check2" value="true"/> <input type="checkbox" name="check3" value="true"/> </form>
$('form').serializeJSON(); // returns => {'check1': 'true'} // Note that check2 and check3 are not included because they are not checked
上面的寫法會忽略未勾選的復(fù)選框。如果需要包含,則可以使用以下方法:
1. 配置checkboxUncheckedValue
$('form').serializeJSON({checkboxUncheckedValue: "false"}); // returns => {'check1': 'true', check2: 'false', check3: 'false'}
2. 添加data-unchecked-value屬性
<form id="checkboxes"> <input type="checkbox" name="checked[bool]" value="true" data-unchecked-value="false" checked/> <input type="checkbox" name="checked[bin]" value="1" data-unchecked-value="0" checked/> <input type="checkbox" name="checked[cool]" value="YUP" checked/> <input type="checkbox" name="unchecked[bool]" value="true" data-unchecked-value="false" /> <input type="checkbox" name="unchecked[bin]" value="1" data-unchecked-value="0" /> <input type="checkbox" name="unchecked[cool]" value="YUP" /> <!-- No unchecked value specified --> </form>
$('form#checkboxes').serializeJSON(); // Note no option is used // returns => { 'checked': { 'bool': 'true', 'bin': '1', 'cool': 'YUP' }, 'unchecked': { 'bool': 'false', 'bin': '0' // Note that unchecked cool does not appear, because it doesn't use data-unchecked-value } }
自動檢測轉(zhuǎn)換類型
默認(rèn)的類型為字符串 :string ,可以通過配置轉(zhuǎn)換為其它類型
$('form').serializeJSON({parseNulls: true, parseNumbers: true}); // returns => { "bool": { "true": "true", // booleans are still strings, because parseBooleans was not set "false": "false", } "number": { "0": 0, // numbers are parsed because parseNumbers: true "1": 1, "2.2": 2.2, "-2.25": -2.25, } "null": null, // "null" strings are converted to null becase parseNulls: true "string": "text is always string", "empty": "" }
在極少數(shù)情況下,可以使用自定義轉(zhuǎn)換函數(shù)
var emptyStringsAndZerosToNulls = function(val, inputName) { if (val === "") return null; // parse empty strings as nulls if (val === 0) return null; // parse 0 as null return val; } $('form').serializeJSON({parseWithFunction: emptyStringsAndZerosToNulls, parseNumbers: true}); // returns => { "bool": { "true": "true", "false": "false", } "number": { "0": null, // <-- parsed with custom function "1": 1, "2.2": 2.2, "-2.25": -2.25, } "null": "null", "string": "text is always string", "empty": null // <-- parsed with custom function }
自定義類型
可以使用 customTypes 配置自定義類型或者覆蓋默認(rèn)類型($.serializeJSON.defaultOptions.defaultTypes)
<form> <input type="text" name="scary:alwaysBoo" value="not boo"/> <input type="text" name="str:string" value="str"/> <input type="text" name="number:number" value="5"/> </form>
$('form').serializeJSON({ customTypes: { alwaysBoo: function(str) { // value is always a string return "boo"; }, string: function(str) { // all strings will now end with " override" return str + " override"; } } }); // returns => { "scary": "boo", // <-- parsed with type :alwaysBoo "str": "str override", // <-- parsed with new type :string (instead of the default) "number": 5, // <-- the default :number still works }
忽略空表單字段
// Select only imputs that have a non-empty value $('form :input[value!=""]').serializeJSON(); // Or filter them from the form obj = $('form').find('input').not('[value=""]').serializeJSON(); // For more complicated filtering, you can use a function obj = $form.find(':input').filter(function () { return $.trim(this.value).length > 0 }).serializeJSON();
使用整數(shù)keys作為數(shù)組的順序
使用useIntKeyAsArrayIndex配置
<form> <input type="text" name="arr[0]" value="foo"/> <input type="text" name="arr[1]" value="var"/> <input type="text" name="arr[5]" value="inn"/> </form>
按照默認(rèn)的方法,結(jié)果為:
$('form').serializeJSON(); // returns => {'arr': {'0': 'foo', '1': 'var', '5': 'inn' }}
使用useIntKeyAsArrayIndex可以將記過轉(zhuǎn)換為數(shù)組并制定順序
$('form').serializeJSON({useIntKeysAsArrayIndex: true}); // returns => {'arr': ['foo', 'var', undefined, undefined, undefined, 'inn']}
默認(rèn)配置Defaults
所有的默認(rèn)配置均定義在 $.serializeJSON.defaultOptions,可以進(jìn)行修改。
$.serializeJSON.defaultOptions.parseAll = true; // parse booleans, numbers and nulls by default $('form').serializeJSON(); // No options => then use $.serializeJSON.defaultOptions // returns => { "bool": { "true": true, "false": false, } "number": { "0": 0, "1": 1, "2.2": 2.2, "-2.25": -2.25, } "null": null, "string": "text is always string", "empty": "" }
總結(jié)
這個插件支持的配置非常豐富,自定義程度很高,帶來很大的便捷性。
以上這篇詳談表單格式化插件jquery.serializeJSON就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- 使用validate.js實現(xiàn)表單數(shù)據(jù)提交前的驗證方法
- jquery序列化form表單使用ajax提交后處理返回的json數(shù)據(jù)
- jquery ajax 如何向jsp提交表單數(shù)據(jù)
- Javascript 詳解封裝from表單數(shù)據(jù)為json串進(jìn)行ajax提交
- form表單數(shù)據(jù)封裝成json格式并提交給服務(wù)器的實現(xiàn)方法
- 基于JavaScript實現(xiàn)帶數(shù)據(jù)驗證和復(fù)選框的表單提交
- 深入分析JSON編碼格式提交表單數(shù)據(jù)
- JavaScript動態(tài)添加數(shù)據(jù)到表單并提交的幾種方式
- asp.net使用JS+form表單Post和Get方式提交數(shù)據(jù)
- 淺析JavaScriptSerializer類的序列化與反序列化
- JS多個表單數(shù)據(jù)提交下的serialize()應(yīng)用實例分析
相關(guān)文章
jquery click([data],fn)使用方法實例介紹
大概意思就是觸發(fā)每一個匹配元素的click事件,本文通過一個實例為大家詳細(xì)介紹下jquery click([data],fn)的使用方法,感興趣的朋友可以參考下哈,希望對大家有所幫助2013-07-07javascript 自定義回調(diào)函數(shù)示例代碼
使用函數(shù)做參數(shù)就有下面的好處:當(dāng)你a(b)的時候函數(shù)b就成了回調(diào)函數(shù),而你還可以a(c)這個時候,函數(shù)c就成了回調(diào)函數(shù)2014-09-09基于jquery擴(kuò)展漂亮的CheckBox(自己編寫)
默認(rèn)的html復(fù)選框控件樣式可定義相當(dāng)有限,下面就與大家分享下自己編寫的CheckBox控件。喜歡的朋友可以拿去使用2013-11-11基于jquery的禁用右鍵、文本選擇功能、復(fù)制按鍵的實現(xiàn)代碼
有時候因為某些原因,需要禁止用戶的右鍵、文本選擇功能、復(fù)制按鍵等操作,那么就可以參考下面的代碼2013-08-08Jquery中的$.each獲取各種返回類型數(shù)據(jù)的使用方法
each()方法能使DOM循環(huán)結(jié)構(gòu)簡潔,不容易出錯。each()函數(shù)封裝了十分強(qiáng)大的遍歷功能,使用也很方便,它可以遍歷一維數(shù)組、多維數(shù)組、DOM, JSON 等等,在javaScript開發(fā)過程中使用$each可以大大的減輕我們的工作量。2015-05-05