十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
小编给大家分享一下表单格式化插件jquery.serializeJSON怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

使用jquery.serializeJSON,可以在基于jQuery或者Zepto的页面中,调用 .serializeJSON() 方法来序列化form表单的数据成JS对象。
使用
只需要在jQuery或者Zepto时候引入即可
示例
HTML form(支持input、textarea、select等标签)
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 转换成字符串(注意IE8兼容性)。
JavaScript权威指南(第6版)(中文版) http://www.gooln.com/document/452.html
var jsonString = JSON.stringify(obj);
指定数据类型
获取到的属性值一般是字符串,可以通过HTML指定类型 : type 进行强制转换。
$('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"}
}
}数据类型也可以指定在 data-value-type 属性中,代替 :type 标记。
options配置
默认配置
Values始终为字符串(除非在input names使用:types )
Keys始终为字符串(默认不自动检测是否需要转换为数组)
未选择的checkboxes会被忽略
disabled的elements会被忽略
自定义配置
包含未勾选的checkboxes
serializeJSON 支持 checkboxUncheckedValue 配置,或者可以在checkboxes添加 data-unchecked-value 属性。
默认方法:
$('form').serializeJSON();
// returns =>
{'check1': 'true'} // Note that check2 and check3 are not included because they are not checked上面的写法会忽略未勾选的复选框。如果需要包含,则可以使用以下方法:
1. 配置checkboxUncheckedValue
$('form').serializeJSON({checkboxUncheckedValue: "false"});
// returns =>
{'check1': 'true', check2: 'false', check3: 'false'}2. 添加data-unchecked-value属性
$('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
}
}自动检测转换类型
默认的类型为字符串 :string ,可以通过配置转换为其它类型
$('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": ""
}在极少数情况下,可以使用自定义转换函数
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 配置自定义类型或者覆盖默认类型($.serializeJSON.defaultOptions.defaultTypes)
$('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();使用整数keys作为数组的顺序
使用useIntKeyAsArrayIndex配置
按照默认的方法,结果为:
$('form').serializeJSON();
// returns =>
{'arr': {'0': 'foo', '1': 'var', '5': 'inn' }}使用useIntKeyAsArrayIndex可以将记过转换为数组并制定顺序
$('form').serializeJSON({useIntKeysAsArrayIndex: true});
// returns =>
{'arr': ['foo', 'var', undefined, undefined, undefined, 'inn']}默认配置Defaults
所有的默认配置均定义在 $.serializeJSON.defaultOptions,可以进行修改。
$.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": ""
}以上是“表单格式化插件jquery.serializeJSON怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联网站建设公司行业资讯频道!
另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。