Javascript Form Serialization Principle and Implementation Code Detailed Explanation

  • 2021-09-11 19:27:57
  • OfStack

With the advent of Ajax, form serialization has become a common requirement. In JavaScript, the form can be serialized using the type property of the form field, along with the name and value properties 1. Before you write the code, you have to figure out how the browser sends data to the server during form submission.

1. Encode the name and value of the form field URL, using the sum number ( & ) Separation.

2. Do not send disabled form fields.

3. Send only checked check boxes and radio buttons.

4. Do not send buttons with type as "reset" and "button".

5. Each selected value in the multiple selection box has a separate entry.

6. When you click the Submit button to submit the form, the Submit button will also be sent; Otherwise, the submit button is not sent.

7. < select > Element is the value of the selected < option > Gets or sets the value of the value attribute of the. If < option > Element does not have the value attribute, the < option > The text value of the element.

During form serialization, 1 generally does not contain any button fields, because the result string is likely to be submitted in other ways. All other above rules should be followed.

Basic form serialization can be achieved by traversing form elements, with the following example code:


function serialize(form){
 var params = [];
 var eles = form.elements;
 
 for (var i = 0;i<ele.length;i++){
  let field = ele[i];
  switch(field.type){
   case "file": 
   case "submit":
   case "reset": 
   case "button":
    break;
   case "radio":
   case "checkbox":
    if(!field.checked){
     break;
    }
    default:
     // Does not contain form fields without names  
     if (field.name.length){ 
      parts.push(encodeURIComponent(field.name) + "=" + 
      encodeURIComponent(field.value)); 
     }
  }
 }
  return parts.join("&");
}

Related articles: