1. Introduction
1.1 Definition
Ajax (Asynchronous Javascript And XML) is a technology that can update some web pages without reloading the entire web page.
By exchanging small amounts of data with the server in the background, Ajax can enable asynchronous updates on web pages. This means that the entire network can be loaded without reloading
1.2 Problems with traditional requests
The browser address bar sends requests synchronously (blocking code running). When the server is very busy, it will stutter (wait), which will cause waste of resources.
1.3 The difference between Ajax request and traditional request
The advantage of ajax data interaction is that it will not block the execution of subsequent js code when requesting data
Execution order of js code with ajax code
1. Execute from top to bottom
2. After encountering ajax code, send the request first
3. Continue to execute other js code downward during the period of waiting for the server to respond to data
4. Wait until the server data response comes back and then execute the rendering data code
1.4 Application scenarios
Whenever we encounter dynamic rendering effects, we should use ajax
2. Native Ajax usage
2.1ajax basic syntax
In essence, ajax is actually a constructor provided in es5 - XMLHttpRequest
The steps for ajax to implement front-end and back-end data interaction are as follows
//1. Create ajax interactive object instantiate it through XMLHTTPRequestlet ajax = new XMLHttpRequest(); //2. Establish a connection between the front-end and the server. There is a method to create a connection by calling the open object.("Request Method","Server url address"); //3. Send request Ajax object has a method to send the request(); //4. Receive server response data. Ajax is an event that passes through the ajax object - onreadystatechange (communication status code/life cycle change event) = ()=>{ //5. Receive response data When the communication status code is 4, the response data can be obtained. if(==4){ if(==200||==304){ () } else{ ("Request failed") } } }
Communication status code/life cycle of ajax
Ajax's communication status code/life cycle has five representative meanings
They are
0: The request is not initialized (the ajax object has not been declared yet)
1: Connection established (the ajax object calls open)
2: The request has been sent (the ajax object calls send)
3: The server receives the request and is processing it
4: The server has responded to data
With the step-by-step recommendation of ajax data interaction, the communication status code/life cycle will automatically change.
Whenever the communication status code/life cycle changes, an onreadystatechange event will be triggered.
In ajax, we can obtain the communication status code/life cycle through a property readyState of the ajax object
ajax object.readyState
We can also get the response data through ajax object's attribute responseText
ajax object.responseText
We can also obtain the response status code through a property status of the ajax object
ajax object.status
2.2ajax submit data
The writing methods of requesting submission data are also different under different request methods. Let’s mainly understand the writing methods of submitting data in the two request methods, get and post.
get
Get request to submit data is added after the address "?key name=key value&key name=key value&..."
//1. Create ajax interactive object instantiate it through XMLHTTPRequestlet ajax = new XMLHttpRequest(); //2. Establish a connection between the front-end and the server. There is a method to create a connection by calling the open object.//Get request to submit data Submit after the address("get","serverurladdress?Key name=Key value&Key name=Key value&..."); //3. Send request Ajax object has a method to send the request(); //4. Receive server response data. Ajax is an event that passes through the ajax object - onreadystatechange (communication status code/life cycle change event) = ()=>{ //5. Receive response data When the communication status code is 4, the response data can be obtained. if(==4){ if(==200||==304){ () } else{ ("Request failed") } } }
post
Post request to submit data is written in the send method. The data to be submitted is passed as an actual parameter of the send method.
Before submitting the post request, you need to set the request header separately. Use the setRequestHeader method of the ajax object to set the request header.
//1. Create ajax interactive object instantiate it through XMLHTTPRequestlet ajax = new XMLHttpRequest(); //2. Establish a connection between the front-end and the server. There is a method to create a connection by calling the open object.//Get request to submit data Submit after the address("post","serverurladdress?Key name=Key value&Key name=Key value&..."); //Set request header("content-type","application/x-www-form-urlencoded"/"application/json") //3. Send request Ajax object has a method to send the request//Pause the data to be submitted as a real parameter into the send method("Key name=Key value&Key name=Key value&..."/({})); //Note: If the data submitted is set to application/json, it must be a json string in object format//4. Receive server response data. Ajax is an event that passes through the ajax object - onreadystatechange (communication status code/life cycle change event) = ()=>{ //5. Receive response data When the communication status code is 4, the response data can be obtained. if(==4){ if(==200||==304){ () } else{ ("Request failed") } } }
When the post request is not submitted, there will be no problem even if the request header is not set. However, in order to achieve semantics and improve the fault tolerance rate, we generally choose to set the request header.
ajax
3.1 Basic usage
jquery's ajax is a method of $ - ajax calls this method and passes the argument to realize ajax data interaction
$(()=>{ //Calling the ajax method to realize data interaction $.ajax({ url:"Server url address",// Must pass type:"Request Method",//Optional default value is get dataType:"Format of data interaction"//Optional default value is json. In addition, you can also select xml text jsonp data:{},//Request submitted data Optional Data is not submitted by default If you want to submit, you can submit it by writing attributes in the object timeout:number,//Timeout time optional. Default is unlimited. If the specific timeout time is set, the timeout will be exceeded after the request is sent. The request will be stopped when the response data has not been received yet. The unit is ms. beforeSend(){ //This method function will be executed before ajax sends the request }, success(res){ //This method function will be executed when ajax sends a request and successfully receives the response data. The formal participation will receive the response data. }, error(err){ //This method function will be executed when ajax fails to receive response data. The formal participation will receive the failure information. }, complete(){ //This method function will be executed when the ajax interaction is completed } }) })
Note: In theory, four methods can not be passed on in the actual parameter object, but success must be passed on in actual development because success is used to receive response data.
3.2JQuery's ajax interaction simplification method
get
Usage: $.get("url address? key-value pair & key-value pair...",(res)=>{ res parameter is used to receive response data })
post
Usage: $.post(url address, {data to be submitted}, (res)=>{ res parameter is used to receive response data })
Principle Description
Ajax's data interaction method Comparison Traditional input address interaction method The biggest advantage is that
It does not block subsequent code
During the period of waiting for response data, the subsequent js code will continue to be executed downward.
The principle of this advantage comes from the distinction and execution order of synchronous asynchronous code of js
The execution order of js synchronous asynchronous code
JS code execution from top to bottom
If you encounter synchronization code, execute it directly
If you encounter asynchronous code, it will be stored in the task queue first and then continue to execute downward
Until all synchronous codes are executed, go to the task queue and remove the asynchronous codes in sequence and execute them in sequence.
Classification of synchronous code and asynchronous code in js
Asynchronous code: event, timer, ajax
Synchronous code: except asynchronous, it is synchronous
Why can ajax code not block the execution of subsequent js code
//1. Create ajax interactive object instantiate it through XMLHTTPRequestlet ajax = new XMLHttpRequest();//Synchronous code//2. Establish a connection between the front-end and the server. There is a method to create a connection by calling the open object.("Request Method","Server url address");//Synchronous code//3. Send request Ajax object has a method to send the request();//Synchronous code//4. Receive server response data. Ajax is an event that passes through the ajax object - onreadystatechange (communication status code/life cycle change event) = ()=>{//Ajax's asynchronous is reflected in events Events are asynchronous code //5. Receive response data When the communication status code is 4, the response data can be obtained. if(==4){ if(==200||==304){ () } else{ ("Request failed") } } }
This is the article about the tutorial on using ajax data interaction tool in front and backend JavaScript. For more related JS ajax content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!