Using native JS to simulate the form serialization, the code for the form processing as much as possible text description, which for URL, field name, Chinese using encodeURIComponent() encoding.

The difference between encodeURI and encodeURIComponent was described in the previous blog

Object.prototype.serialize = function(){
	var res = [],	// An array of results
		current = null.// The form control in the current loop
		i,	// Index of the form NodeList
		len, // The length of form NodeList
		k,	//select traversal index
		optionLen,	//select traversal index
		option, //select options in the loop
		optionValue,	/ / select the value
		form = this;	// Use the form variable to get the current form
	
	for(i=0, len=form.elements.length; i<len; i++){
		
		current = form.elements[i];
		
		//disabled Indicates that fields are disabled and must be distinguished from readonly
		if(current.disabled) continue;
		
		switch(current.type){
			
			// Control processing can be ignored
			case "file":	// File input type
			case "submit":	// Submit button
			case "button":	// Common buttons
			case "image":	// Submit button in image form
			case "reset":	// Reset button
			case undefined:	/ / undefined
				break;
			
			/ / select control
			case "select-one":
			case "select-multiple":
				if(current.name && current.name.length){
					console.log(current)
					for(k=0, optionLen=current.options.length; k<optionLen; k++){

						option = current.options[k];
						optionValue = "";
						if(option.selected){
							if(option.hasAttribute){
								optionValue = option.hasAttribute('value')? option.value : option.text }else{
								// Lower versions of IE need to use the specified attribute of the feature to check whether an attribute has been specified
								optionValue = option.attributes('value').specified ? option.value : option.text;	
							}
							res.push(encodeURIComponent(current.name) + "=" + encodeURIComponent(optionValue)); }}}break;
				
			// Single, check box
			case "radio":
			case "checkbox":
				// There is a trick here, where the judgment is corresponding to the following default.
				// If placed elsewhere, additional judgment values are required
				if(! current.checked)break;
			
			default:
				// General form control processing
				if(current.name && current.name.length){
					res.push(encodeURIComponent(current.name) + "=" + encodeURIComponent(current.value)); }}}return res.join("&");
}
Copy the code

For HTML forms:

formElement.serialize();
Copy the code

A =1&b=2&c=3&d=4&e=5