We all know that there is a way to serialize the form in jquery:
1.serialize () method
Format: var data = $ ("form"). Serialize ();
Function: Serializes the contents of the form into a single string.
This way, when Ajax submits the form data, it is not necessary to enumerate each parameter. Simply set the data parameter to $ ("form"). Serialize ().
2.serializeArray () method
Format: var jsondata = $ ("form"). Serializearray ();
Function: Serializes a page form into a JSON-structured object. Note that it is not a JSON string.
For example, [{"Name": "Lihui", "Age": "20"},{...}] get data for Jsondata[0].name
Below we use the original sound JS to implement our form form to serialize the function;
First we set out the steps:
1) First obtain form forms using Byid or forms;
2) Gets an array of all the elements in the form after being fetched by elements;
3) After the traversal judgment type (according to the type of the corresponding object splicing) to achieve the serialization of objects;
The code is as follows:
1 functionFormser (form) {2 varform=document.getElementById (form);3 varArr={};4 for(vari = 0; i < form.elements.length; i++) {5 varFeled=Form.elements[i];6 Switch(feled.type) {7 Caseundefined:8 Case' Button ':9 Case' File ':Ten Case' Reset ': One Case' Submit ': A Break; - Case' checkbox ': - Case' Radio ': the if(!feled.checked) { - Break; - } - default: + if(Arr[feled.name]) { -arr[feled.name]=arr[feled.name]+ ', ' +Feled.value; +}Else{ Aarr[feled.name]=Feled.value; at - } - } - } - returnarr -},
Native JS Implementation Form form serialization