>  기사  >  웹 프론트엔드  >  양식 서식 지정 플러그인 jquery.serializeJSON에 대한 자세한 설명

양식 서식 지정 플러그인 jquery.serializeJSON에 대한 자세한 설명

小云云
小云云원래의
2018-01-06 10:53:043462검색

이 문서에서는 주로 양식 형식 지정 플러그인 jquery.serializeJSON에 대해 자세히 설명합니다. 편집자님이 꽤 좋다고 생각하셔서 지금 공유하고 모두에게 참고용으로 드리도록 하겠습니다. 편집자를 따라 살펴보겠습니다. 모두에게 도움이 되기를 바랍니다.

Foreword

프런트 엔드에서 대량의 데이터 제출이 포함된 양식을 처리할 때 양식을 사용하여 페이지를 직접 제출하고 새로 고칠 때 자주 발생하는 요구 사항은 양식 정보를 데이터 개체로 수집하고 이를 통해 제출하는 것입니다. 아약스.

복잡한 양식을 다룰 때에는 필드 값을 일일이 수동으로 판단하고 처리해야 하는데, 이는 매우 번거로운 작업입니다. 다음에 소개되는 플러그인은 이 문제를 해결할 것입니다.

serializeJSON 정보

jquery.serializeJSON을 사용하면 .serializeJSON() 메서드를 호출하여 jQuery 또는 Zepto 기반 페이지의 양식 데이터를 JS 개체로 직렬화할 수 있습니다.

사용하려면

jQuery 또는 Zepto

 <script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.serializejson.js"></script>

Example

HTML 형식에 도입하면 됩니다(입력, 텍스트 영역, 선택 및 기타 태그 지원)

<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를 사용하여 문자열로 변환할 수 있습니다(IE8 호환성 참고).

JavaScript 최종 가이드(6판)(중국어 버전) http://www.gooln.com/document/452.html

 var jsonString = JSON.stringify(obj);

데이터 유형 지정

얻어진 속성 값은 일반적으로 문자열입니다. HTML 지정 유형을 전달할 수 있습니다: 강제 변환을 위한 유형입니다.

<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=&#39;{"my": "stuff"}&#39;/>
</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"}
  }
}

데이터 유형은 :type 태그 대신 data-value-type 속성에서 지정할 수도 있습니다.

<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>

옵션 구성

기본 구성

값은 항상 문자열입니다(입력 이름에 :types를 사용하지 않는 한)

키는 항상 문자열입니다(기본값은 배열로 변환해야 하는지 자동으로 감지하지 않습니다)

선택하지 않은 체크박스는 무시됩니다

비활성화된 요소는 무시됩니다

사용자 정의 구성

체크되지 않은 체크박스를 포함합니다

serializeJSON은 checkboxUncheckedValue 구성을 지원합니다. 또는 체크박스에 data-unchecked-value 속성을 추가할 수 있습니다.

기본 방법:

<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

위 작성 방법은 선택되지 않은 확인란을 무시합니다. 이를 포함해야 하는 경우 다음 방법을 사용할 수 있습니다.

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
 }
}

자동으로 변환 유형 감지

기본 유형은 문자열입니다. 구성을 통해 변환할 수 있습니다. 다른 유형의 경우

$('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>
 <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
$(&#39;form :input[value!=""]&#39;).serializeJSON();
 
// Or filter them from the form
obj = $(&#39;form&#39;).find(&#39;input&#39;).not(&#39;[value=""]&#39;).serializeJSON();
 
// For more complicated filtering, you can use a function
obj = $form.find(&#39;:input&#39;).filter(function () {
     return $.trim(this.value).length > 0
   }).serializeJSON();

정수 키를 배열 순서로 사용

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>

기본 방법에 따른 결과는 다음과 같습니다.

$('form').serializeJSON();
 
// returns =>
{'arr': {'0': 'foo', '1': 'var', '5': 'inn' }}

useIntKeyAsArrayIndex를 사용하여 단점을 배열로 변환하고 지정합니다. order

$('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": ""
}

요약

이 플러그인은 매우 풍부한 구성과 높은 수준의 사용자 정의를 지원하므로 매우 편리합니다.

관련 권장 사항:

Sublime Text 3에 코드 형식 지정 플러그인 CodeFormatter 설치

jquery 기반 웹 페이지 날짜 형식 지정 플러그인_jquery

Sublime Text 3에 코드 형식 지정 플러그인 CodeFormatter 설치

위 내용은 양식 서식 지정 플러그인 jquery.serializeJSON에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.