Note source: Hook Education – big front end employment Training camp

Content: Notes, thoughts and experiences in the process of learning

Use of cross-domain and template engines

Cross-domain problems and same-origin policies

The same-origin policy

  • The same domain name, protocol, and port are the same
  • Under the same-origin policy, only same-origin addresses can communicate with each other through AJAX
  • Same-origin refers to the relationship between two addresses. The request between addresses of different sources is called cross-domain

HTTP (protocol)://www.baidu.com(domain name):80(port - default 80 is not written)/index.html

Browsers do not allow cross-domain data acquisition, but in modern Web applications, we need to obtain resources from different source addresses, so we must solve the problem of different sources to achieve cross-domain data request

JSONP

JSON with Padding, a method of sending cross-domain requests with script tags

Basic Principles:

  • The client requests an address from the server via the script tag
  • Script Returns a JS script with a global function call as the result
  • This function call will call one of our local JS functions
  • And the arguments to the function are the data we want

Jsonp can only send GET requests, and jSONP has nothing to do with XHR

The json in JQ

With the $.ajax() method, you simply set the dataType type to JSONP

<body>
  <! -- Create button -->
  <input type="button" value="Get">
  <script>
    // button adds click events
    $('input').click(function () {
      // Get data in jSONP mode
      $.ajax({
        // Address: this is a Baidu search text prompt interface
        url: 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web'.// 方式使用get
        type: 'get'.// Set dataType to jSONp to get data in jSONp mode
        dataType: 'jsonp'.// The name of the jSONp callback function can be set here, otherwise JQ will automatically generate a name
        jsonpCallback: 'abc'.// We can change the parameter name of the callback function, the default is callback, but if the interface requires the parameter name, we need to manually set the same as the interface requires
        jsonp: 'cd'.// Data to be passed in
        data: {
          wd: 'ajax'
        },
        // Prints the returned data
        success: function (data) {
          console.log(data)
        }
      })
    })
    // In most cases, you do not need to set the name and parameters of the callback function
  </script>
</body>
Copy the code

CORS cross-domain

Cross Origin Resource Share — Cross-domain Resource Share

There is no need to make any changes on the client side, just add an Access-Control-Allow-Origin response header to the server response indicating whether the resource supports the specified domain request

Access – Control – Allow – the value of Origin

  • An asterisk (*) indicates that any source can access the file across domains and is not secure
  • The value is (a domain name + protocol) for example:http://foo.comIndicates that only the specified source is allowed access

Cors cross-domain is now more commonly used

Case study: Baidu search

Analog Baidu search when the automatic prompt

  1. Let’s try it at Baidu, go to console Network, look at the file response and see the name of the callback functionJQuery110202399796524493838_1611211395892 (parameters), indicating that it is sent in a JSONP format
  2. Open headers to find the function namecb=jQuery110202399796524493838_1611211395892&_=1611211395894, so the parameter is called CD
  3. The actual received parameters are wd:&wd=12(I’m searching for 12.)
  4. The interface address ishttps://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web
<! DOCTYPEhtml
  PUBLIC "- / / / / W3C DTD XHTML 1.0 Transitional / / EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Stair navigation effect</title>
  <script src="./js/jquery.min.js"></script>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    ul {
      list-style: none;
    }

    .box {
      width: 500px;
      margin: 100px auto;
    }

    .box .l {
      float: left;
      width: 396px;
      border: 2px solid #4e6ef3;
      overflow: hidden;
    }

    .box .l input {
      width: 396px;
      height: 36px;
      border: 0;
      outline: none;
    }

    .box .r {
      float: right;
      width: 100px;
      height: 40px;
      border: 0;
      background-color: #4e6ef3;
      color: #fff;
    }
  </style>
</head>

<body>
  <div class="box">
    <div class="l">
      <input type="text">
      <ul>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
      </ul>
    </div>
    <input class="r" type="button" value="Google it.">
  </div>
  <script>
    // Get the element
    const $lis = $('.box .l ul li'),
      $input = $('.box .l input')
    // Add a keyboard lift event to the input box
    $input.keyup(function () {
      // Cross-domain request
      $.ajax({
        url: 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web'./ / the json
        dataType: 'jsonp'.// Set the parameter to cb
        jsonp: 'cb'.// Set parameters
        data: {
          wd: $(this).val()
        },
        // Use the returned data to ul
        success: function (data) {
          if (data.g === undefined) {
            return
          }
          $lis.each(function (i) {$(this).text(data.g[i].q)
          })
        }
      })
    })
  </script>
</body>

</html>
Copy the code

Template engines

  • Reducing string concatenation
  • Parsing JSON in templates and then concatenating it with HTML content gives better performance

ArtTemplate Template Engine (Tencent)

Simple, super fast template engine

Address: github.com/aui/artTemp…

Aui.github. IO /art-templat…

Common syntax:

  • <% js code %>Statements wrapped in symbols are template logical expressions
  • <%= expression %>Is the output expression

use

  1. Introduce template JS files
  2. Create a template
  3. Data template binding
  4. Writing parsed data
  5. Bind the data and template to get the content
  6. Data is written to the page
<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Use the template engine</title>
  <! Jquery -->
  <script src="./js/jquery.min.js"></script>
  <! -- Introduced template engine altTelplate -->
  <script src="./js/template-web.js"></script>
  <! Create a template engine, id is the first parameter, type is text/ HTML -->
  <script id="tem" type="text/html">
    <! <% %> is required before and after using the template js code.
  <! -- Use <%= %> wrap if you want to use expressions like variables -->
  <% for(let i = 0; i < 5; i++){ %>
  <li>I was created inside the template <%= I %></li>The < %} % ><! Use the second argument of template to specify the value of the property.
  <li>I am data in array <%= name%></li>
  </script>
</head>

<body>
  <div class="box">
    <ul class="list"></ul>
  </div>
  <script>
    // Create an array
    const arr = [{
      name: 1
    }, {
      name: 2
    }, {
      name: 3
    }, {
      name: 4
    }, {
      name: 5
    }, {
      name: 6},]// Loop through the array, passing each object in the array into the template method
    for (const i of arr) {
      The template method takes two arguments: the id value of the template to be used and the data of the object type to be used. The template can use the property name of the object directly to obtain the value of the property
      // loop to add li to ul
      $('.box .list').append(template('tem', i))
    }
  </script>
</body>

</html>
Copy the code

Use template engine to transform Baidu case

<! DOCTYPEhtml
  PUBLIC "- / / / / W3C DTD XHTML 1.0 Transitional / / EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>baidu</title>
  <! -- Introduce template engine -->
  <script src="./js/template-web.js"></script>
  <! -- // add jq -->
  <script src="./js/jquery.min.js"></script>
  <! Create template -->
  <script id="tem" type="text/html">
    <! -- Loop over g property -->
    <% for(let i = 0; i < g.length; i++){ %>
  <! Create li with q attribute for each g content -->
  <li><%= g[i].q %></li>The < %} % ></script>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    ul {
      list-style: none;
    }

    .box {
      width: 500px;
      margin: 100px auto;
    }

    .box .l {
      float: left;
      width: 396px;
      border: 2px solid #4e6ef3;
      overflow: hidden;
    }

    .box .l input {
      width: 396px;
      height: 36px;
      border: 0;
      outline: none;
    }

    .box .r {
      float: right;
      width: 100px;
      height: 40px;
      border: 0;
      background-color: #4e6ef3;
      color: #fff;
    }
  </style>
</head>

<body>
  <div class="box">
    <div class="l">
      <input type="text">
      <ul>
        <! Add structure generated by template engine here -->
      </ul>
    </div>
    <input class="r" type="button" value="Google it.">
  </div>
  <script>
    // Get the element
    const $ul = $('.box .l ul'),
      $input = $('.box .l input')
    // Add a keyboard lift event to the input box
    $input.keyup(function () {
      // Cross-domain request
      $.ajax({
        url: 'https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web'./ / the json
        dataType: 'jsonp'.// Set the parameter to cb
        jsonp: 'cb'.// Set parameters
        data: {
          wd: $(this).val()
        },
        // Use the returned data to ul
        success: function (data) {
          // Check whether the data exists
          if (data.g === undefined) {
            return
          }
          // Call the template engine to add the result to ul
          $ul.html(template('tem', data))
        }
      })
    })
  </script>
</body>

</html>
Copy the code

Case in point: message boards

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Document</title>
  <! -- Add CSS style files -->
  <link rel="stylesheet" href="css/index.css">
  <! Import template engine file -->
  <script src="./js/template-native.js"></script>
  <! -- Reference jq file -->
  <script src="Js/jquery - 1.12.4. Min. Js." "></script>
  <! Create template -->
  <script id="tem" type="text/html">
    <! -- Loop over the input data, pass in a data object with an array of comments properties, loop over all the data below the list -->
    <% for(let i = 0; i < comments.length; i++){ %>
  <! Write structure and call value in data -->
  <! Create a custom attribute on li and mark your location in the database.
  <li uid="<%= comments[i].id%>">
    <p class="floor">< % = comments [I]. Id % ><a href="javascript:;" class="delete">delete</a></p>
    <p class="author"><%= comments[I].username%><span class="name"></span></p>
    <p class="content"><%= comments[i].content%></p>
  </li>The < %} % ></script>
</head>

<body>
  <! -- -- -- > structure
  <div class="main">
    <div class="post">
      <h2>Happy New Year!</h2>
      <p class="author">Building Lord: line crazy</p>
      <p class="txt">In the New Year, I wish you all a happy New Year, good health, promotion and pay rise!</p>
    </div>
    <div class="reply">
      <h4>reply</h4>
      <p>User name:<input type="text" class="reply"></p>
      <textarea class="editor"></textarea>
      <input type="button" value="Published" class="btn">
    </div>
    <div class="cmts">
      <ul class="list">
        <! -- Add messages to this -->
      </ul>
    </div>
  </div>
  <script>
    // Get the element
    const $list = $('.main .cmts .list'),
      $user = $('.reply input:text'),
      $textarea = $('.reply textarea'),
      $btn = $('.reply .btn')
    // Initialize, use get to get data, call template engine to modify the message board list
    $.get('http://localhost:3000/db'.function (data) {
      $list.html(template('tem', data))
      // Call the function to add the delete function to each delete button
      del()
    })
    // Publish button click events
    $btn.click(function () {
      // Check whether it is empty. If it is empty, prompt the user
      if ($user.val() === ' ' || $textarea.val() === ' ') {
        alert('Incorrect input')
        return
      }
      // Execute the following code if not null
      // Add data to the database using the pose method
      $.post('http://localhost:3000/comments', {
        username: $user.val(),
        content: $textarea.val()
      }, function (data) {
        // The returned data is substituted into the template, but the template needs to be an object and the object needs to have an array of comments properties, so manually emulate the object
        $list.append(template('tem', {
          comments: [data]
        }))
        // The newly added delete button has no delete function, we add delete function here for all delete button call
        del()
      })
    })
    // Delete button ah add delete function
    function del() {
      // Add click events to each button
      $('.delete').click(function () {
        // Delete the data from the database, locate the ancestor of the delete button li tag, and delete the element according to the custom attribute value of the li tag
        $.ajax({
          url: `http://localhost:3000/comments/The ${$(this).parents('li').attr('uid')}`.type: 'delete'
        })
        // Find the li tag of the ancestor of the delete button and delete it
        $(this).parents('li').remove()
      })
    }
  </script>
</body>

</html>
Copy the code
{
  "comments": [{"id": 4."username": "Jiang Jiang"."content": "Call the landlord ~ +10000"
    },
    {
      "username": "West poison"."content": "General owner of the building"."id": 6
    },
    {
      "username": "Ashes of time"."content": "Ha ha ha ha."."id": 7}}]Copy the code