When the front-end processes forms that contain a large amount of data submission, in addition to using Form to directly submit and refresh the page, the often encountered requirement is to collect form information into data objects and submit them via Ajax.
When dealing with complex forms, you need to manually judge and process field values one by one, which is very troublesome. The plugin introduced next will solve this problem.
Usingjquery.serializeJSON
, you can call the.serializeJSON()
method to serialize in a page based on jQuery or Zepto The form data is converted into JS objects.
you only need to introduce it when jQuery or Zepto
HTML form
(supportsinput
,textarea
,select
etc. Tags)
##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?1.1.10", language: "javascript", popular: "0" } }, selectOne: "rock", selectMultiple: ["red", "blue"] }
serializeJSONmethod returns a JS object, not JSON string. You can use
JSON.stringifyto convert to a string (note IE8 compatibility).
var jsonString = JSON.stringify(obj);
$('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-typeattribute, replace the
:typetag.
:typesis used in
input names)
Keysare always String (default does not automatically detect whether it needs to be converted to an array)
checkboxeswill be ignored
disabledelements
will be ignored
写法 释义 checkboxUncheckedValue: string 针对未勾选的checkboxes,设定值 parseBooleans: true 自动检测转换”true”、”false”为布尔值true、false parseNumbers: true 自动检测转换”1″、”33.33″、”-44″为数字1、33.33、-44 parseNulls: true 自动检测字符串”null”为null parseAll: true 自动检测转换以上类型的字符串 parseWithFunction: function 自定义转换函数 function(value, name){return parsedValue}customTypes: {} 自定义:types覆盖默认types,如{type: function(value){…}} defaultTypes: {defaultTypes} 重新定义所有的:types,如{type: function(value){…}} useIntKeysAsArrayIndex: true 当keys为整数时,将序列化为数组
checkboxUncheckedValueconfiguration, or you can add
data-unchecked-value incheckboxes
Attributes.
$('form').serializeJSON(); // returns =>{'check1': 'true'} // Note that check2 and check3 are not included because they are not checked
checkboxUncheckedValue
$('form').serializeJSON({checkboxUncheckedValue: "false"}); // returns =>{'check1': 'true', check2: 'false', check3: 'false'}
data-unchecked-valueattribute
$('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, which can be converted to other types through configuration
$('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 formobj = $('form').find('input').not('[value=""]').serializeJSON(); // For more complicated filtering, you can use a functionobj = $form.find(':input').filter(function () { return $.trim(this.value).length > 0 }).serializeJSON();
使用useIntKeyAsArrayIndex
配置
按照默认的方法,结果为:
$('form').serializeJSON(); // returns =>{'arr': {'0': 'foo', '1': 'var', '5': 'inn' }}
使用useIntKeyAsArrayIndex
可以将记过转换为数组并制定顺序
$('form').serializeJSON({useIntKeysAsArrayIndex: true}); // returns =>{'arr': ['foo', 'var', undefined, undefined, undefined, 'inn']}
所有的默认配置均定义在$.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": ""}
这个插件支持的配置非常丰富,自定义程度很高,带来很大的便捷性。
The above is the detailed content of Form formatting plug-in jquery.serializeJSON. For more information, please follow other related articles on the PHP Chinese website!