Understanding AJAX
AJAX
full name async javascript and xml
Is the ability to interact with the front and back
That is, the tool for our client to send messages to the server, and the tool for receiving responses
It is a function of the default asynchronous execution mechanism
Previously:
Enter something in the browser address bar to display a page
Enter a php address in the browser address bar, and the content returned by php is given to the browser
It is:
js to request a php address
The content of PHP output will not be displayed directly on the browser
Instead, the content returned by PHP is given to the language js
If you still want him to be displayed on the page, then you need js to render, such as: document.write()
AJAX asynchronous
Four steps to use AJAX
Create an ajax object, synchronize the code
Configuration request information, synchronization code
Send request, asynchronous code
Determine whether it is a "synchronous request" or "asynchronous request" according to the third parameter of open
But it is asynchronous code
Accept response, asynchronous code
Writing suggestions
Asynchronous request:
The order of writing codes is: 1–>2–>3–>4
The writing order can also be: 1–>2–>4–>3
Synchronization request:
The writing order must be: 1–>2–>4–>3
in conclusion:
No matter if you send a synchronous or asynchronous request
Our code writing order is: 1–>2–>4–>3
Suggest:
Don’t send synchronous ajax requests as a last resort
Use of AJAX
There is a built-in constructor in js to create AJAX objects
After creating the AJAX object, we use the method of the AJAX object to send requests and receive responses
1. Create an AJAX object
The ajax object can help us send ajax requests
const xhr = new XMLHttpRequest ( )
const xhr = new ActiveXObject ( 'Mricosoft.XMLHTTP' ) ;
2. Configure link information
The open method in the AJAX object is to configure the request information
xhr.open('请求方式','请求地址','是否异步');
The first parameter: the request method of this request: get, post, put
The second parameter: is the URL address of this request
The third parameter: whether this request is asynchronous or not, the default true means asynchronous, false means synchronous
const xhr = new XMLHttpRequest ( ) ;
xhr. open ( 'get' , './date.php' ) ;
4. Accept the response
Because js and php interact, the output content of php is given to js, so an event is used to receive
const xhr = new XMLHttpRequest ( ) ;
xhr. open ( 'get' , './date.php' ) ;
xhr. onload = function ( ) {
console. log ( '请求已经完成' ) ;
console. log ( xhr) ;
console. log ( xhr. response) ;
document. getElementById ( 'box' ) . innerHTML = xhr. response;
}
xhr. onreadystatechange = function ( ) {
if ( xhr. readyState== 4 && /^2\d{2}$/ . test ( xhr. status) ) {
console. log ( '确定状态码是4' ) ;
console. log ( xhr. status) ;
console. log ( xhr. responseText) ;
}
}
3. Send the request
Use the ajax object.send() method
Means to send out this request that I configured
const xhr = new XMLHttpRequest ( ) ;
xhr. open ( 'get' , './deta.php' ) ;
xhr. onload = function ( ) {
console. log ( '请求已经完成' ) ;
console. log ( xhr) ;
console. log ( xhr. response) ;
}
xhr. send ( ) ;
Receive response
AJAX status code
AJAX status code- xhr.readyState
It is used to represent a certain state in the entire process of an AJAX request
readyState === 0
: Indicates that the initialization is not completed, that is, the open
method has not been executed
readyState === 1
l: Indicates that the configuration information has been completed, that is, the execution is complete open
readyState === 2
: Indicates that the send
method has been executed
readyState === 3
: Indicates that the response content is being parsed
readyState === 4
: Indicates that the response content has been parsed and can be used on the client
At this time, we will find that in the entire process of an AJAX request, only when readyState===4
, we can use the data that the server gives us normally.
Therefore, with http status code 200-299
There is a member in an AJAX object called xhr.status
This member records the http status code of this request
When both conditions are met, the request is completed normally
readyStateChange
There is an event in the AJAX object, called readyStateChange
event
This event is specifically used to monitor readyState
the behavior of the AJAX object's value change
That is, as long as readyState
the value changes, then the event will be triggered
So we are monitoring AJAX in this event to see if it has readyState
reached 4
const xhr = new XMLHttpRequest ( ) ;
xhr. open ( 'get' , './data.php' ) ;
xhr. send ( ) ;
xhr. onreadyStateChange = function ( ) {
if ( xhr. readyState === 4 && /^2\d{2}$/ . test ( xhr. status) ) {
console. log ( xhr. responseText) ;
}
}
responseText
responseText
Members in the AJAX object
It is used to record the content of the response body given to us by the server
So we can use this member to get the content of the response body
const xhr = new XMLHttpRequest ( ) ;
xhr. open ( 'get' , './data.php' ) ;
xhr. send ( ) ;
xhr. onreadyStateChange = function ( ) {
if ( xhr. readyState === 4 && /^2\d{2}$/ . test ( xhr. status) ) {
/ 我们在这里直接打印xhr. reaponseText 来查看服务端给我们返回的内容
console. log ( xhr. responseText) ;
}
}
Carry parameters when using AJAX to send a request
We use AJAX to send requests can also carry parameters
Parameters are some information given to him when interacting with the background
But there is still a difference between the two methods of carrying parameters get and post
Send a get request with parameters
The parameters of the get request can be spliced directly after the url.
const xhr = new XMLHttpRequest ( ) ;
xhr. open ( 'get' , './date.php?a=100$b==200' ) ;
xhr. send ( ) ;
- 这样服务端就能接受到两个参数
- 一个是a,值是100
- 一个是b,值是200
Send a post request with parameters
The parameters of the post request are carried in the request body, so there is no need to splice after the url
application/x-www=form-urlencoded
The data format represented is key=value&key=value
const xhr = new XMLHttpRequest ( ) ;
xhr. open ( 'get' , './data.php' ) ;
xhr. setRequesHeader ( 'content-type' , 'application/x-www-form-urlencoded' ) ;
xhr. send ( 'a=100&b=200' ) ;
Encapsulate AJAX
Ajax is too troublesome to use, because you have to write a lot of code every time
Then we encapsulate an ajax method to make it easier for us to use
Decide how to use it
Because there are some content that can not be passed, we can use the default value, so choose the way the object passes the parameters
ajax ( {
url: '' ,
type: '' ,
async : '' ,
data: '' ,
dataType: '' ,
success: function ( ) {
}
} )
Encapsulation
function ajax ( options) {
var defInfo = {
url: '' ,
type: 'GET' ,
async : false ,
data: '' ,
dataType: 'string' ,
success ( ) {
} ,
}
if ( ! options. url) {
throw new Error ( 'url 必须传递' )
}
for ( let key in options) {
defInfo[ key] = options[ key]
}
if ( ! ( typeof defInfo. data === 'string' && /^(\w+=\w+&?)*$/ . test ( defInfo. data) || Object. prototype. toString. call ( defInfo. data) === '[object Object]' ) ) {
throw new Error ( '请按照要求传递参数' )
}
if ( typeof defInfo. async !== 'boolean' ) {
throw new Error ( 'async 参数只接受布尔数据类型' )
}
if ( ! ( defInfo. type. toUpperCase ( ) === 'GET' || defInfo. type. toUpperCase ( ) === 'POST' ) ) {
throw new Error ( '目前本插件只接受 GET 和 POST 方式,请期待更新' )
}
if ( Object. prototype. toString. call ( defInfo. success) !== '[object Function]' ) {
throw new Error ( 'success 只接受函数数据类型' )
}
var str = ''
if ( Object. prototype. toString. call ( defInfo. data) === '[object Object]' ) {
for ( let attr in defInfo. data) {
str += ` ${
attr} = ${
defInfo. data[ attr] } &`
}
str = str. slice ( 0 , - 1 )
defInfo. data = str
}
function createXHR ( ) {
if ( XMLHttpRequest) {
return new XMLHttpRequest ( )
} else {
return new ActiveXObject ( 'Microsoft.XMLHTTP' )
}
}
var xhr = createXHR ( )
xhr. open ( defInfo. type, defInfo. url + ( defInfo. type. toUpperCase ( ) === 'GET' ? `? ${
defInfo. data} &_= ${
new Date ( ) . getTime ( ) } ` : '' ) , defInfo. async )
if ( defInfo. type. toUpperCase ( ) === 'POST' ) {
xhr. setRequestHeader ( 'content-type' , 'application/x-www-form-urlencoded' )
}
xhr. send ( ( defInfo. type. toUpperCase ( ) === 'POST' ? ` ${
defInfo. data} ` : '' ) )
xhr. onreadystatechange = function ( ) {
if ( xhr. readyState === 4 && /2\d{2}/ . test ( xhr. status) ) {
if ( defInfo. dataType === 'json' ) {
defInfo. success ( JSON . parse ( xhr. responseText) )
} else {
defInfo. success ( )
}
}
}
}