This is the 23rd day of my participation in Gwen Challenge

Send form information using AJAX

Why use AJAX to send form data?

When sending using a form, an error message is always displayed on the second page if it fails. Poor user experience.

When sending using AJAX, an error message is displayed on this page once it fails. You can modify it directly without performing other operations.

Form serialization

If the form itself is submitted, the data is organized by the browser. When submitting form data using AJAX, you can only organize the data yourself. One or two form controls, easy to say, or one or two forms. However, new forms will always appear, and the structure of forms will always change. At this point, assembling the data yourself one by one can seem cumbersome. So we define a function that helps us serialize the data in the form.

Application scenario for form serialization: Submit data for the entire form using AJAX

Why form serialization: No one helped us organize the data in the form

Serialization functions in jQuery

$(form).serialize(); Return value: a string of keys and values for all controls in the form

The demo:

$("form").serialize();
Copy the code

console:

Self-wrapped serialization functions

For example:

This function takes a form element as an argument and returns a string of all the control names and values for that form element
function serialize(form) {
	// Define a string
	var str = ' ';
	// Get all the form controls
	// var elements = form.elements;
	var elements = form.getElementsByTagName("*");
	// Filter out all controls with the name attribute
	var arr = [];
	// Loop through all elements
	for(var i = 0; i < elements.length; i++) {
		// Determine if the name attribute is present
		if(elements[i].name) { arr.push(elements[i]); }}// Match one by one
	for(var i = 0; i < arr.length; i++) {
		 if (arr[i].type === "text" || arr[i].type === "password" || arr[i].type === "select-one" || arr[i].type === "textarea" ) {
		 	 str += arr[i].name + "=" + encodeURIComponent(arr[i].value) + "&";
		 } else if (arr[i].type === "radio" && arr[i].checked) {
		 		str += arr[i].name + "=" + encodeURIComponent(arr[i].value) + "&";
		 }
	}
	str = str.slice(0, -1);
	return str;
}
Copy the code

transcoding

Because the URL can not have Chinese, so need to transcode.

Transcoding functions

EncodeURIComponent is a transcoding function that transcodes

There are strings like this

var str = "Username = wanglaow5 &password=123&sex=male&age=18&suggest=aaaa"
Copy the code

Transcoding:

var str1 = encodeURIComponent(str);
Copy the code

Transcoding result:

The decoding function

DecodeURIComponent decodeURIComponent decodeURIComponent decodeURIComponent decodeURIComponent decodeURIComponent decodeURIComponent

var str = "username=%E7%8E%8B%E8%80%81%E4%BA%94&password=123&sex=male&age=18"
Copy the code

Decoding:

var result = decodeURIComponent(str);
Copy the code

Decoding result:

"Username = password= 123sex =male&age=18"
Copy the code

Waterfall flow

Waterfall flow refers to a page model.

The feature is that the page spreads down as the user navigates the page. It’s like a waterfall.

Waterfall flow layout

We find that the waterfall flow of petal net belongs to constant width waterfall flow, and each column is of equal width.

We took 99 images and talked about layout

Code 1:

var lis = document.getElementsByTagName("li");
for(var i = 0; i < 100; i++) {
	var img = new Image();
	img.src = "img/" + i + ".png";
	lis[i % 3].appendChild(img)
}
Copy the code

Conclusion: It is found that the bottom of the page is uneven because the height of each picture is not consistent.

Improved: Go up the tree according to height

// We now decide to climb the tree according to the height
var lis = document.getElementsByTagName("li");
// Define a height mapping array
var arr = new Array(lis.length).fill(0);
/ / loop
for(var i = 0; i < 100; i++) {
	var img = new Image();
	img.src = "img/" + i + ".png";
	img.onload = function() {
		// Get the index of the smallest item in the array
		var idx = getMinIdx(arr); 
		// find the corresponding li
		lis[idx].appendChild(this); 
		// The height of the tree li has changed and the value of li's mapping array should also change
		arr[idx] += this.height; }}// Define a function to get the smallest index in the array
function getMinIdx(arr) {
	var idx = 0;
	var min = arr[idx];
	for(var i = 1; i < arr.length; i++) {
		if (min > arr[i]) { // If the minimum value is greater than the next value, the minimum value should be replaced and the subscript value replacedmin = arr[i]; idx = i; }}return idx;
}
Copy the code

Tree on the way

After AJAX requests data back, you want to put that content up the tree for the user to see. There are several ways.

The first way is up the tree

If you have a few elements, create a few elements.

Cons: Too much code.

The second way up the tree

No matter how many elements there are in a structure, only the outermost element is created. Concatenate the inner element as the innerHTML of the outer element.

Advantages: Better than the first

Disadvantages: When the DOM structure is complex, it is difficult to distinguish the structure.

The third way up the tree

Use template engine mode.

Define templates: Write content inside a script tag that cannot be executed

<script type="text/template" id="tpl">
	<div class="container">
		<div class="item">
			<span>The user name</span><span><%username%></span>
		</div>
		<div class="item">
			<span>gender</span><span><%sex%></span>
		</div>
		<div class="item">
			<span>age</span><span><%age%></span>
		</div>
		<div class="item">
			<div class="type">
				<span>The card type</span><span><%card.type%></span>
			</div>
			<div class="num">
				<span>The card number</span><span><%card.number%></span>
			</div>
			<div class="yue">
				<span>The balance of</span><span><%card.money%></span>
			</div>
		</div>
	</div>
</script>
Copy the code

Definition dictionary: Data returned from AJAX requests

{
	"error": 0."data": {
		"username": "wanglaowu"."age": 13."sex": "nan"."card": {
			"type": China Merchants Bank."number": 19823619823173."money": 25}}}Copy the code

Formatting: Combine templates with dictionaries.

// Define a function that takes two arguments the first is a template string and the second is an object
function format(tplStr, dictionary) {
	// The substitution method replaces something in the string
	return tplStr.replace(/<%((\w+)(\.\w+)*)%>/g.function(match, $1) {
		// Set $1 to. Split into arrays
		var arr = $1.split(".");
		var result = dictionary;
		// Loop arR to fetch data from the dictionary
		for(var i = 0; i < arr.length - 1; i++) {
			result = result[arr[i]];
		}
		returnresult[arr[i]]; }}) callsvar str_format = format(str, data.data)
Copy the code

Up tree: Up tree

msg.html(str_format)
Copy the code

underscore

This is a JS utility library. The variable name is underscore: _

There are many functional programming style features.

Only the _. Template function is covered here

This function is used to format templates

Step 1: Put the defined string template into the function

// Define a string template
var tpl_str = "<div><%=name%></div>"
// generate the function
var format = _.template(tpl_str);
Copy the code

At this point, format is a function that is bound to the tpl_str string template. Whenever you want to generate a template for the TPL_str structure, call format and pass the dictionary.

Step 2: Call format and pass the dictionary

format({name: "Wang Lao Wu"})
Copy the code

Step 3: Results

<div> Wang Laowu </div>Copy the code

Underscore: This is a JS tool library that contains many commonly used JS methods such as filter, map, reduce, some, etc