AJAX

  • ajaxThe full nameasync javascript and XML
  • It’s the ability to interact front and back
  • That is, the tool that our client sends the message to the server, and the tool that receives the response
  • Is a function of the default asynchronous execution mechanism

The advantage of AJAX

1. Native JS can be used without plug-in support

2. Good user experience (data can be updated without page refresh)

3, reduce the burden of server and bandwidth

4, disadvantages: the support of the search engine is not enough, because the data is not on the page, the search engine search

The use of AJAX

  • There are built-in constructors in JS to create Ajax objects
  • Once the Ajax objects are created, we use ajax object methods to send requests and receive responses

Create an Ajax object

// IE9 and above
const xhr = new XMLHttpRequest()
​
/ / ie 9 below
const xhr = new ActiveXObject('Mricosoft.XMLHTTP')
Copy the code
  • So you have an Ajax object up there
  • We can use this XHR object to send ajax requests

Configuring Link Information

const xhr = new XMLHttpRequest()
​
// The open method in the XHR object configures the request information
Get/post/put /...
// The second parameter is the URL for this request
// The third parameter is whether the request is asynchronous. The default value is true for asynchronous and false for synchronous
// xhr.open(' request mode ', 'request address ', whether asynchronous)
xhr.open('get'.'./data.php'After the above code is executed, the basic configuration information for this request is written and the request is sentconst xhr = new XMLHttpRequest()
xhr.open('get'.'./data.php')
​
// Use the send method in the XHR object to send the request
xhr.send()
Copy the code
  • The code above sends the configured Ajax object to the server

A basic Ajax request

  • One of the most basic Ajax requests is the above three steps
  • But with the above three steps, we can actually send the request to the server
  • If the server is healthy, the response can also go back to the client
  • But we can’t get a response
  • If we want to get a response, we have two conditions

2. Ajax objects also have their own status codes, which are used to represent the various stages of the Ajax request

Ajax status code

  • Ajax status code – xhr.readyState

  • Is used to represent a state in the entire course of an Ajax request

    • readyState === 0: indicates that the initialization is not complete, that is, the open method has not been executed
    • readyState === 1: indicates that the configuration information is complete, that is, after the open command is executed
    • 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 is parsed and can be used on the client
  • At this point we’ll see that we can only use the data from the server if readyState === 4 throughout an Ajax request

  • Therefore, the HTTP status code ranges from 200 to 299

    • An Ajax object has a member calledxhr.status
    • This member records the HTTP status code for this request
  • The request is completed only when both conditions are met

readyStateChange

  • There is an event in the Ajax object calledreadyStateChangeThe event
  • This event is specifically used to listen for Ajax objectsreadyStateThe act of changing value
  • In other words, as long asreadyStateThe event is triggered when the value of
  • So we’re going to listen for Ajax in this eventreadyStateI don’t know if it’s 4
const xhr = new XMLHttpRequest()
xhr.open('get'.'./data.php')
​
xhr.send()
​
xhr.onreadyStateChange = function () {
 // This event is emitted every time readyState changes
 // We can check if readyState is 4
 // The HTTP status code is 200 to 299
 if (xhr.readyState === 4 && /^2\d{2|$/.test(xhr.status)) {
 // This indicates that the authentication is successful
 // We can get the content of the response from the server}}Copy the code

responseText

  • ResponseText member in the Ajax object
  • It is used to record the contents of the response body that the server gives us
  • So we just use this member to get the response body content
const xhr = new XMLHttpRequest()
xhr.open('get'.'./data.php')
​
xhr.send()
​
xhr.onreadyStateChange = function () {
 if (xhr.readyState === 4 && /^2\d{2|$/.test(xhr.status)) {
 // Here we print xhr.responseText directly to see what the server returns to us
 console.log(xhr.responseText)
  }
}
Copy the code

You use Ajax to send requests with parameters

  • We can also use Ajax to send requests with parameters
  • Parameters are the information given to the background when interacting with it
  • But there are differences between get and POST that take parameters

Send a GET request with parameters

  • The parameters of the GET request are concatenated directly after the URL
const xhr = new XMLHttpRequest()
// Add an address directly after the address. , and pass it as key=value
// Two data are separated by &
xhr.open('get'.'./data.php? a=100&b=200')
​
xhr.send()
Copy the code
  • This allows the server to accept two parameters
  • One is a, and the value is 100
  • One is B, and the value is 200

Send a POST request with parameters

  • The parameters of the POST request are carried in the request body, so they do not need to be concatenated after the URL
const xhr = new XMLHttpRequest()
xhr.open('post'.'./data.php')
​
// If you are sending post requests using Ajax objects, you must first set the content-Type in the request header
// Tell the server what kind of data format I gave you
xhr.setRequestHeader('content-type'.'application/x-www-form-urlencoded')
​
// The request body should be put in ()
Key =value&key=value
xhr.send('a=100&b=200')
Copy the code
  • application/x-www-form-urlencodedThe data format of the representation iskey=value&key=value

The same-origin policy

  • The same origin policy is given by the browser

  • Browsers don’t allow us to send requests to other people, only to our own servers

  • When we try to send a request to someone else’s server, the browser blocks it

  • What is “someone else’s server”?

    • When the request protocol/domain name/port number is either different, then it is someone else’s server
    • The same-origin policy is triggered at this point
  • A request that triggers the same origin policy is called a cross-domain request

Implement a cross-domain request

  • Sometimes we need to implement cross-domain requests
  • We need multiple servers to feed data to a page
  • So at this point we have to figure out how to solve the cross-domain problem

JSONP

  • jsonpIt’s a way for us to make cross-domain requests, it’s just a technical way to put together what we had before
  • This is done using the script tag

The nature of the script tag

  • The browser gives us a script tag

  • Its essence is to request an external resource and is not affected by the same origin policy

  • The SRC attribute of the script tag, which is also a request, can also be received by the server

  • And:

    • The SRC attribute of the script tag requests back a string that the browser executes as JS code
  • So we can use the SRC attribute of the script tag to make cross-domain requests

Configuring the proxy (Understanding)

  • There are two types of proxies, forward and reverse

Forward agent

  • There is a client that needs to send a request to a non-homogeneous server B
  • We set up A server with the same origin as the client
  • When the client sends A request, server A receives it
  • The request is then sent from server A to server B, because the same origin policy is given by the browser, not between servers
  • After server B receives the request, it processes the request and returns the response to server A
  • Server A then sends the response to the client
  • We can make cross-domain requests in this way

The reverse proxy

  • Reverse proxy is generally used for load balancing
  • When I request a server, I’m actually requesting a proxy server set up on the server side
  • A proxy server distributes a number of requests to different servers for processing
  • The server sends the response to the proxy server
  • The proxy server returns to the client

Encapsulation AJAX

  • Ajax is too cumbersome to use because you have to write a lot of code each time
  • So let’s encapsulate an Ajax method to make it easier to use

Be sure to use it

  • Since there are some things we can leave unpassed, we can use the default values, so we choose how the object passes the parameters
// Async: ", // async: ", // whether async: ", // dataType: Parse success: function () {} parse success: function () {})Copy the code
  • Once you’ve decided how to use it, you start writing the wrapper function

encapsulation

function ajax(options) {
  // Prepare a default value
  var defInfo = {
    url: ' '.// The address does not need a default value
    type: 'GET'.// The default value for request mode is GET
    async: false.// The default value is asynchronous
    data: ' '.// The parameter has no default value
    dataType: 'string'.Json.parse is not required by default
    success () {}, // The default is a function
  }
​
  // Check whether the URL is passed. If not, throw an exception
  if(! options.url) {throw new Error('URL must be passed')}// Once we have the URL, we merge the user-passed parameters with our default data
  for (let key in options) {
    defInfo[key] = options[key]
  }
​
  // We'll just use our defInfo for everything else
  // The first step is to determine the parameter data
  // Data can not be passed, can be null
  // Data can also be a string of key=value&key=value format
  // Data can also be an object
  // Otherwise, an exception is thrown
  if(! (typeof defInfo.data === 'string' && /^(\w+=\w+&?) * $/.test(defInfo.data) || Object.prototype.toString.call(defInfo.data) === '[object Object]')) {
    throw new Error('Please pass parameters as required')}// Determine the data type of async
  // Only Boolean data types can be passed
  if (typeofdefInfo.async ! = ='boolean') {
    throw new Error('Async parameters only accept Boolean data types')}// Determine type next
  We only accept GET or POST requests
  if(! (defInfo.type.toUpperCase() ==='GET' || defInfo.type.toUpperCase() === 'POST')) {
    throw new Error('Currently this plugin only accepts GET and POST, please look forward to updates')}// Success is a function
  if (Object.prototype.toString.call(defInfo.success) ! = ='[object Function]') {
    throw new Error('Success only accepts function data types')}// There are no problems with the parameters
  // We need to process the data
  // Since data can be an object, when data is an object, we need to convert it to a string
  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
  }
​
  // With all the parameters verified, we can start normal Ajax requests
  // 1. Prepare an Ajax object
  // Since we are dealing with compatibility issues, we prepare a function
  function createXHR() {
    if (XMLHttpRequest) {
      return new XMLHttpRequest()
    } else {
      return new ActiveXObject('Microsoft.XMLHTTP')}}// create an Ajax object
  var xhr = createXHR()
​
  // 3
  xhr.open(defInfo.type, defInfo.url + (defInfo.type.toUpperCase() === 'GET' ? `?${defInfo.data}& _ =The ${new Date().getTime()}` : ' '), defInfo.async)
​
  if (defInfo.type.toUpperCase() === 'POST') {
    xhr.setRequestHeader('content-type'.'application/x-www-form-urlencoded')}// 4. Send
  xhr.send((defInfo.type.toUpperCase() === 'POST' ? `${defInfo.data}` : ' '))
​
  // 5. Accept the response
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && /2\d{2}/.test(xhr.status)) {
      // We will execute success
      // But use dataType judgment
      if (defInfo.dataType === 'json') {
        defInfo.success(JSON.parse(xhr.responseText))
      } else {
        defInfo.success()
      }
    }
  }
}
Copy the code

More recommended

  • JavaScript Learning Notes (26) – cookie
  • JavaScript Learning Notes (25) – HTTP
  • MYSQL > MYSQL > MYSQL
  • JavaScript Learning Notes (23) – Server PHP