AJAX-04 (homology & cross domain) (anti shake & throttling)

1. Homology Strategy & cross domain

1. Homology: two URL addresses have the same protocol, host name and port number.

The Same origin policy is a security function provided by the browser.

The browser's homology policy stipulates that resource interaction between non homologous URL s is not allowed.

2. Cross domain:

Homology means that the protocol, host name and port number of two URL s are exactly the same. On the contrary, it means cross domain.

The root cause of cross domain: the browser's homology policy does not allow resource interaction between non homologous URL s.

For example:

Webpage: http://www.test.com/index.html

Interface: http://www.api.com/userlist

Restricted by the same origin policy, the above web page request and the following interface will fail!

Browser's interception of cross domain requests

The browser allows cross domain requests to be initiated. However, the data returned from cross domain requests will be intercepted by the browser and cannot be obtained by the page! The schematic diagram is as follows:

3. Three solutions to cross domain restrictions:

JSONP and CORS are two technical solutions to realize cross domain data requests.

Note: at present, JSONP is rarely used in actual development. CORS is a cross domain mainstream technology solution. Reverse proxy

programmeTime of birthProgramme sourcesadvantageshortcoming
JSONPAppear earlierPrivate (Unofficial)Good compatibility (compatible with low version IE)Only GET requests are supported
CORSLate appearanceW3C official standardSupport common request methods such as GET, POST, PUT, DELETE and PATCHIncompatible with some older browsers
1.CORS technology requires both browser and server support, both of which are indispensable:
  • The browser shall support CORS function (all mainstream browsers support it, IE shall not be lower than IE10)
  • The server needs to enable the CORS function (the back-end developer needs to enable the CORS function for the interface)

Principle of CORS: the server tells the browser whether the current API interface allows cross domain requests through the access control allow origin response header.

Two main advantages of CORS:

CORS is a real Ajax request. It supports GET, POST, DELETE, PUT, PATCH and other common Ajax request methods. You only need to turn on the CORS function at the back end, and there is no need to change the code at the front end

Note: in the case we have done before, the CORS function has been enabled on the server side for all the called interfaces! For example: chat robot case, news list case, user login case

2.JSONP is a technical solution for cross domain data requests.

It only supports GET requests, not POST, DELETE and other requests.

It is rarely used in actual development, and the principle of JSONP may be asked in the interview

When solving cross domain problems:

The CORS scheme uses the XMLHttpRequest object, which initiates pure Ajax requests

The JSONP scheme does not use the XMLHttpRequest object, so JSONP is not a real Ajax technology

Conclusion: as long as the XMLHttpRequest object is used, the Ajax request is initiated!

Underlying implementation principle of JSONP:

JSONP uses the src attribute of the script tag at the bottom! The src attribute of the script tag is not limited by the browser's homology policy. It can request non homologous JavaScript code locally and execute it

3. Reverse proxy: the essence is that ajax needs data from its own server, let its own server go to a third-party server to get the data, and then its own server returns the data to the browser

2. Anti shake & throttling

1. debounce means that when an operation is triggered frequently, only the last time is executed.

The essence of anti shake: use the setTimeout delayer to trigger events again per unit time to clear the last event

Scenario: the query request is executed only after the search box is entered.

Benefits: this can effectively reduce the number of requests and save network resources.

Core code:

2. Anti shake case: Taobao Search case
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Taobao Search case</title>
  <!-- Import the basic style of the page -->
  <link rel="stylesheet" href="./css/search.css" />
</head>

<body>
  <div class="container">
    <!-- Logo -->
    <img src="./images/taobao_logo.png" alt="" class="logo" />

    <div class="box">
      <!-- tab column -->
      <div class="tabs">
        <div class="tab-active">baby</div>
        <div>shop</div>
      </div>
     <!-- Search area (search box and search button) -->
      <div class="search-box">
        <input type="text" class="ipt" placeholder="Please enter the content to search" /><button class="btnSearch">
          search
        </button>
      </div>

      <!-- Search suggestion list -->
      <div id="suggest-list">
        <div class="suggest-item">Search suggestion 1</div>
        <div class="suggest-item">Search suggestion 2</div>
        <div class="suggest-item">Search suggestion 3</div>
        <div class="suggest-item">Search suggestion 4</div>
      </div>
    </div>
  </div>


  <!-- Import axios -->
  <script src="./lib/axios.js"></script>
  <script>

    axios.defaults.baseURL = 'http://www.liulongbin.top:3009'
    // debounce means that when an operation is triggered frequently, only the last time is executed.
    // The essence of anti shake: use the setTimeout delayer to re trigger the event in the unit event and clear the last event
    // The search box executes the query request only after entering.

    //4. Declare an empty timeID 
    let timeId = null
    // 1. Listen for input events
    document.querySelector('.ipt').oninput = function () {

      //If there is continuous input within 5.5 milliseconds, clear the last timer, then re obtain the text, and repeat this operation until the user stops input and prints on the console
      clearTimeout(timeId)

      // 2. Get text
      let txt = this.value

      //Judgment of data legitimacy and suggestions for clearing keywords when they are empty
      if (txt.trim().length === 0) return document.querySelector('#suggest-list').innerHTML = ''

      // 3. Start the timer and print the search box text after 5ms
      timeId = setTimeout(function () {
        console.log(txt);

        getSuggestList(txt)
      }, 500)
    }

    //Claim get advice
    function getSuggestList(txt) {
      axios({
        url: '/api/sug',
        method: 'get',
        params: {
          q: txt
        }
      }).then(({ data: res }) => {
        //Successful callback
        console.log(res)
        let htmlArr = []
        res.result.forEach(value => {
          htmlArr.push(`
            <div class="suggest-item">${value}</div>
          `)
        });
        document.querySelector('#suggest-list').innerHTML = htmlArr.join('')
      })
    }
  </script>
</body>
</html>
3. Throttling means that the same operation is triggered frequently in unit time, which will only be triggered for the first time.

Essence of throttling: use a variable flag (throttle valve) to set the state, which is a Boolean value of true or false

Core code:

4. Case: bullet shooting
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./lib/bootstrap-v4.6.0.css">
  <link rel="stylesheet" href="./lib/throttle.css">
</head>

<body>

  <!-- Outer box -->
  <div class="box">
    <!-- Si Cong -->
    <img src="./img/photo.gif" class="photo" alt="">
  </div>

  <!-- Launch button -->
  <button class="btn btn-primary btn-fire">Fire</button>

  <script src="./lib/jquery-v3.6.0.js"></script>
  <script>
    $(function () {

      // Throttling: if the same operation is triggered frequently in a unit time, it will only be triggered once
      // Essence of throttling: use a variable flag (throttle valve) to set the state, which is a Boolean value of true or false

      // Whether the next bullet can be fired (true: indicates that it can be fired, false: indicates that it cannot be fired)
      let flag = true

      $('.btn-fire').on('click', function () {
        // Whenever a click event is triggered, first judge whether bullets can be fired (if not, return; if yes, set the flag to false immediately)
        if (flag === false) return
        flag = false

        // 1. Dynamically create DOM objects for bullets
        const newBall = $('<img src="./img/bullet.png" class="ball" alt="" />')
        // 2. Add bullets to the box on the page
        $('.box').append(newBall)
        // 3. Execute animation
        newBall.animate({ left: '95%' }, 1000, 'linear', function () {
          // When the animation is complete, remove the bullet
          $(this).remove()

          // After the bullet is destroyed, reset the flag to true, indicating that the next bullet can be fired
          flag = true
        })
      })

    })
  </script>
</body>

</html>
5. Summary:

Be able to know how to convert between JSON and JS objects

  • JSON.parse( )
  • JSON.stringify( )

Be able to say the implementation principle of JSONP

  • The src attribute of the script tag is not affected by the same origin policy. The server responds by calling a function

Be able to say what throttling and anti shake are

  • Anti shake: events are triggered frequently, and only the last time is executed
  • Throttling: frequently triggered events are executed only once per unit time

Keywords: Front-end Ajax http

Added by Scud on Wed, 12 Jan 2022 23:04:10 +0200