Ajax study notes organization

1. Client and Server

1.1 Server

In the process of surfing the Internet, the computer responsible for storing and providing resources to the outside world is called a server.

1.2 Client

In the process of surfing the Internet, the computer responsible for acquiring and consuming resources is called the client.

2.URL address

2.1 The concept of URL address

The Chinese name of URL is Uniform Resource Locator, which is used to represent the unique storage location of each resource on the Internet. Only through the URL address, the browser can correctly locate the storage location of the resource, so as to successfully access the corresponding resource

2.2 Components of URL Addresses

A URL address generally consists of three parts:

  1. Communication protocol between client and server
  2. The name of the server where the resource is stored
  3. The specific storage location of the resource on the server

3. Communication process between client and server

3.1 Illustrate the communication process between the client and the server

Note: 1. The communication process between the client and the server is divided into three steps: request-processing-response

‚Äč 2. Every resource in the web page is obtained from the server through request-processing-response

4. What resources does the server provide externally

4.1 Data is also a resource

The data in the web page is also a resource provided by the server to the outside world.

4.2 How to request data in web pages

Data is also a resource provided by the server to the outside world. As long as it is a resource, it must be obtained through a request-processing-response method.

If you want to request data resources on the server in a web page, you need to use the XMLHttpRequest object

XMLHttpRequest (referred to as xhr) is a js member provided by the browser, through which data resources on the server can be requested.

Simplest usage: var xhrObj=new XMLHttpRequest()

4.3 How to request resources

When a client requests a server, there are many ways of requesting, and the two most common request ways are get and post requests.

  • The get request is usually used to obtain server-side resources (require resources from the server-side)

    For example: Obtain HTML files, css files, js files, image files, data resources, etc. from the server according to the URL address

  • post requests are usually used to submit data to the server (send resources to the server)

    For example, login is various data submission operations such as login information submitted to the server, registration information submitted to the server when registering, user information submitted to the server when adding a user, etc.

5. Understand Ajax

5.1 What is Ajax

Ajax (Asynchronous Javascript and XML). Popular understanding: the way to use the XMLHttpRequest object to interact with the server in the web page is Ajax

5.2 Typical application scenarios of Ajax

1. Username detection: When registering a user, dynamically monitor whether the username is occupied by means of Ajax

2. Search hints: When entering search keywords, the list of search hints is dynamically loaded in the form of ajax

3. Paging display of data: when the page number value is clicked, the data of the table is dynamically refreshed according to the page number value in the form of Ajax

4. Data addition, deletion, modification, and query: data addition, deletion, access, query, and operation all need to use the form of Ajax to realize data interaction

6. Ajax in jQuery

The three most common ways to initiate Ajax requests in jQuery are as follows:

  • $.get()
  • $.post()
  • $.ajax()

6.1 $.get() function

1. Grammar

The $.get() function in jQuery has a single function and is specially used to initiate a get request, so as to request resources on the server to the client for use.

The syntax of $.get() is as follows:

$.get(url, [data], [callback]);

2. $.get() initiates a request without parameters

When using the $.get() function to initiate a request without parameters, you can directly provide the requested URL address and the callback function after the request is successful. The sample code is as follows:

$.get('http://www.liulongbin.top:3006/api/getbooks',function(res) {
    console.log(res);//Here res is the data returned by the server
})
3. $.get() initiates a request with parameters

Use the $.get() function to initiate a request with parameters, the sample code is as follows:

//Request information with id 1
$.get('http://www.liulongbin.top:3006/api/getbooks',{id:1},function(res) {
    console.log(res);//Here res is the data returned by the server
})

6.2 $.post() function

1. Grammar

The syntax of $.post() is as follows:

$.post(url, [data], [callback]);

2. $.post() submits data to the server

Use the $.post() function to submit data to the server, the sample code is as follows:

$.post('http://www.liulongbin.top:3006/api/addbook',{bookname:'Water Margin',author:'Shi Naian',publisher:'Shanghai Book Publishing House'},function(res) {
    console.log(res);
})

6.3 $.ajax() function

1. Grammar
$.ajax({
    type:'',//The method of the request, such as GET or POST
    url:'',	//the requested url address
    data:{ },//The data to be carried in this request
    success:function(res) { }//Callback function after successful request
})
2. Use $.ajax() to initiate a GET request

When using $.ajax() to initiate a GET request, simply set the value of the type attribute to 'GET':

$.ajax({
    type:'GET',//way of request
    url:'http://www.liulongbin.top:3006/api/getbooks',//The requested url address
    data:{id:1},//The data to be carried in this request
    success:function(res) {//Callback function after successful request
        console.log(res);
    }
})
3. Use $.ajax() to initiate a POST request

When using $.ajax() to initiate a POST request, simply set the value of the type attribute to 'POST':

$.ajax({
    type:'POST',//way of request
    url:'http://www.liulongbin.top:3006/api/addbook',//The requested url address
    data:{
        bookname:'bbh',
        author:'Shi Nai'an',
        publisher:'Shanghai Book Publishing House'
    },//data to submit to the server
    success:function(res) {//Callback function after successful request
        console.log(res);
    }
})

7. Interface

7.1 The concept of interface

When using Ajax to request data, the requested URL address is called the data interface (referred to as the interface). At the same time, each interface must have a request method.

E.g:

http://www.liulongbin.top:3006/api/getbooks Interface to get book list (GET request)

http://www.liulongbin.top:3006/api/addbook Add book interface (POST request)

7.2 Analyze the request process of the interface

1. The process of requesting the interface through GET

2. The process of requesting the interface through POST

7.3 Interface Documentation

1. What is an interface document

The interface document, as the name suggests, is the description document of the interface, which is the basis for us to call the interface. A good interface document contains the description of the interface URL, parameters and output content. We can easily guide the function of the interface and how to call the interface by referring to the interface document.

2. Components of the interface documentation

An interface document can contain a lot of information, and can also be simplified as needed. However, a qualified interface document should contain the following six contents, which provide the basis for the interface invocation:

  1. Interface name: a simple description used to indicate each interface, such as: login interface, book list access interface, etc.
  2. Interface URL: the calling address of the interface
  3. Calling method: the calling method of the interface, such as: GET, POST
  4. Parameter format: The parameters that the interface needs to pass, each parameter must contain the parameter name, parameter type, whether it is required, and parameter description.
  5. Response format: a detailed description of the return value of the interface, generally including data name, data type, and data description 3 items
  6. Return example (optional): In the form of an object, exemplify the structure of the data returned by the server

8. Basic use of form forms

8.1 What is a form

The form is mainly responsible for the data collection function in the web page. The tags in HTML are used to collect the information input by the user, and submit the collected information to the server for processing through the submission operation of the tags.

8.2 Components of a form

A form consists of three basic parts:

  • form tag
  • Form fields: Contains text boxes, password boxes, hidden fields, multi-line text boxes, check boxes, radio boxes, drop-down selection boxes, and file upload boxes, etc.
  • form button

8.3 Attributes of the form tag

Tags are used to collect data, and attributes of tags are used to specify How to send the collected data to the server.
Attributesvaluedescribe
actionURL addressSpecifies where to send form data when the form is submitted
methodget or postSpecifies how to submit form data to the action URL
enctypeapplication/x-www-form-urlencoded multipart/form-data text/plainSpecifies how to encode form data before sending it
target_blank _self _parent _top framenameSpecifies where to open the action URL
1.action

The action attribute is used to specify where to send the form data when the form is submitted

The value of the action attribute should be a URL address provided by the backend, which is responsible for accepting the data submitted by the form

When the form does not specify the action attribute, the default value of the action is the URL address of the current page

Note: When the form is submitted, the page will immediately jump to the URL address specified by the action attribute

2.target

The target attribute is used to specify where to open the actionURL.

There are 5 optional values. By default, the value of target is _self, which means that the action URL is opened in the same frame.

valuedescribe
_blankOpen in new window.
_self default. Open in the same frame.
_parentOpen in the parent frameset. (Rarely used)
_topOpen in the whole window. (Rarely used)
framenameOpen in the specified frame. (Rarely used)
3.method

The method attribute is used to specify how the form data is submitted to the action URL

It has two optional values, namely get and post

By default, the value of method is get, which means that the form data is submitted to the action URL in the form of a URL address.

Notice:

The get method is suitable for submitting a small amount of simple data.

The post method is suitable for submitting large, complex, or including file upload data.

In actual development, the form's post submission method is used the most, and get is rarely used. For example, form operations such as login, registration, and adding data need to use the post method to submit the form.

4.enctype

The enctype attribute is used to specify how the form data should be encoded before sending it.

It has three optional values. By default, the value of enctype is application/x-www-form-urlencoded, which means that all characters are encoded before sending.

valuedescribe
application/x-www-form-urlencodedEncode all characters before sending (default)
multipart/form-dataDoes not encode characters. This value is required when using a form that contains a file upload control.
text/plainSpaces are converted to "+" plus signs, but special characters are not encoded. (Rarely used)

Notice:

When it comes to file upload operations, the value of enctype must be set to multipart/form-data

If the form submission does not involve a file upload operation, simply set the value of enctype to application/x-www-form-urlencoded !

8.4 Synchronous submission of forms and disadvantages

1. What is synchronous submission of forms

By clicking the submit button, the form submission operation is triggered, so that the page jumps to the action URL, which is called synchronous submission of the form

2. Disadvantages of synchronous submission of forms
  • 1. After the form is submitted synchronously, the entire page will jump to the address pointed to by the action URL, and the user experience is very poor
  • 2. After the form is submitted synchronously, the previous state and data of the page will be lost
3. Solve the shortcomings of form synchronous submission

Solution: The form is only responsible for collecting data, and Ajax is responsible for submitting the data to the server

9. Submit form data via Ajax

9.1 Listen to the form submit event

In jQuery, you can use the following two ways to listen to the submit event of the form:

$('#form1').submit(function(e) {
   alert('Listening to the submit event of the form')
})

$('#form1').on('submit', function(e) {
   alert('Listening to the submit event of the form')
})

9.2 Prevent the default submit behavior of forms

After listening to the submission event of the form, you can call the event.preventDefault() function of the event object to prevent the submission of the form and the jump of the page. The sample code is as follows:

$('#form1').submit(function(e) {
   // Prevent form submission and page jumping
   e.preventDefault()
})

$('#form1').on('submit', function(e) {
   // Prevent form submission and page jumping
   e.preventDefault()
})

9.3 Quickly get the data in the form

1.serialize() function

In order to simplify the data acquisition operation in the form, jQuery provides the serialize() function whose syntax is as follows:

$(selector).serialize()

The advantage of the serialize() function: you can get all the data in the form at one time

2.serialize() function example
<form id="form1">
    <input type="text" name="username" />
    <input type="password" name="password" />
    <button type="submit">submit</button>
</form>
$('#form1').serialize()
// The result of the call:
// username=value of username&password=value of password

Note: When using the serialize() function to quickly get form data, you must add a name attribute to each form element!

10. Basic Concepts of Template Engines

10.1 Problems encountered when rendering UI structures

var rows=[];
$.each(res.data,function(i,item) {
	rows.push('<li class="list-group-item">'+item.content
	+'<span class="badge cmt-date">Comment time:'
	+item.time+'</span><span class="badge cmt-person">Commentator:'
	+item.username+'</span></li>')			
})
$('#cmt-list').empty().append(rows.join(''))//The UI structure of the rendering list

The above code renders the UI structure in the form of string splicing

If the UI structure is complex, you need to pay special attention to the nesting between quotation marks when splicing strings, and once the requirements change, it is very troublesome to modify

10.2 What is a template engine

The template engine, as the name suggests, can automatically generate a complete HTML page according to the template structure and data specified by the programmer

10.3 Benefits of Template Engines

  • Reduced string concatenation operations
  • Make the code structure clear
  • Make code easier to read and maintain

11.art-template template engine

11.1 Usage steps

  1. import art-template
  2. define data
  3. define template
  4. call template function

11.2 art-template standard syntax

1. What is standard syntax

art-template provides a syntax format of {{ }}. In {{ }}, you can perform variable output, or loop array operations. This {{ }} syntax is called standard syntax in art-template.

2. Standard syntax - output

{{value}}

{{obj.key}}

{{obj['key']}}

{{a?b:c}}

{{a||b}}

{{a+b}}

In the {{ }} syntax, variable output, object property output, ternary expression output, logical OR output, addition, subtraction, multiplication and division can be output by expressions such as

3. Standard syntax - original text output

{{@ value}}

If the value to be output contains the HTML tag structure, you need to use the original text output to ensure that the HTML tag is rendered normally.

4. Standard syntax - conditional output

If you want to achieve conditional output, you can use if ... else if ... /if in {{ }} to output on demand

{{if value}} output on demand {{/if}}

{{if v1}}On-demand output{{else if v2}}On-demand output{{/if}}

5. Standard syntax - loop output

If you want to achieve loop output, you can loop the array through the each statement within {{ }}, the index of the current loop is accessed using $ index, and the current loop item is accessed using $ value

{{each}}
 		{{$index}} {{$value}}
{{/each}}
6. Standard Syntax - Filter

The essence of the filter is a function handler

{{value | filterName}}

The filter syntax is similar to the pipe operator, its previous output is used as the next input

Basic syntax for defining filters:

template.defaults.imports.filterName = function(value) { /* return the result of processing */ }

E.g:

12. Implementation principle of template engine

12.1 Regular and String Operations

1. Basic grammar

The exec() function is used to retrieve the match of the regular expression in the string, if there is a matching value in the string, it returns the matching value, otherwise it returns null

RegExpObject.exec(string)

The sample code is as follows:

var str = 'hello'
var pattern = /o/
// Output result["o", index: 4, input: "hello", groups: undefined]
console.log(pattern.exec(str)) 
2. Grouping

The content enclosed by ( ) in the regular expression represents a group, and you can extract the content you want by grouping. The sample code is as follows:

var str = '<div>I'm{{name}}</div>'
 var pattern = /{{([a-zA-Z]+)}}/

 var patternResult = pattern.exec(str)
 console.log(patternResult)
 // Get group information related to name
 // ["{{name}}", "name", index: 7, input: "<div>I am {{name}}</div>", groups: undefined]
3. String replace function

The replace() function is used to replace some characters with other characters in a string. The syntax is as follows:

var result = '123456'.replace('123', 'abc') // The value of result obtained is the string 'abc456'
4. Multiple replace ments
var str = '<div>{{name}}This year{{ age }}Years old</div>'
var pattern = /{{\s*([a-zA-Z]+)\s*}}/

var patternResult = pattern.exec(str)
str = str.replace(patternResult[0], patternResult[1])
console.log(str) // Output <div>name is {{ age }} this year</div>

patternResult = pattern.exec(str)
str = str.replace(patternResult[0], patternResult[1])
console.log(str) // Output <div>name is age this year</div>

patternResult = pattern.exec(str)
console.log(patternResult) // output null
5. Use a while loop to replace
var str = '<div>{{name}}This year{{ age }}Years old</div>'
var pattern = /{{\s*([a-zA-Z]+)\s*}}/

var patternResult = null
while(patternResult = pattern.exec(str)) {
   str = str.replace(patternResult[0], patternResult[1])
}
console.log(str) // Output <div>name is age this year</div>
6.replace with true value
var data = { name: 'Zhang San', age: 20 }
var str = '<div>{{name}}This year{{ age }}Years old</div>'
var pattern = /{{\s*([a-zA-Z]+)\s*}}/

var patternResult = null
while ((patternResult = pattern.exec(str))) {
   str = str.replace(patternResult[0], data[patternResult[1]])
}
console.log(str)

12.2 Implementing a Simple Template Engine

1. Implementation steps
  1. Define template structure
  2. Pre-invoked template engine
  3. Encapsulate template function
  4. Import and use a custom template engine
2. Define the template structure
<!-- Define template structure -->
<script type="text/html" id="tpl-user">
   <div>Name:{{name}}</div>
   <div>age:{{ age }}</div>
   <div>gender:{{  gender}}</div>
   <div>address:{{address  }}</div>
</script>
3. Pre-call template engine
<script>
   // define data
   var data = { name: 'zs', age: 28, gender: 'male', address: 'Mapo, Shunyi, Beijing' }
   // call template function
   var htmlStr = template('tpl-user', data)
   // Render HTML structure
   document.getElementById('user-box').innerHTML = htmlStr
</script>

4. Encapsulate the template function
function template(id, data) {
  var str = document.getElementById(id).innerHTML
  var pattern = /{{\s*([a-zA-Z]+)\s*}}/
  var pattResult = null
  while ((pattResult = pattern.exec(str))) {
    str = str.replace(pattResult[0], data[pattResult[1]])
  }
  return str
}

Tags: Front-end Ajax

Posted by farsighted on Fri, 16 Sep 2022 21:47:28 +0300