Front and rear end separation

Posted by Welling on Sun, 02 Jan 2022 17:09:46 +0100

How to send HTTP requests with js

ajax (Asynchronous Javascript And Xml), commonly known as ajax, refers to sending HTTP requests through js and processing the resulting responses

There are many kinds of ajax, and we can use one of them: XMLHttpRequest object for processing

var xhr = new XMLHttpRequest();
xhr.open("GET". " /user-list.json");//Send GET or POST
xhr.send(); /Send request

For security, ajax is only allowed to be sent under the same domain page by default, such as www.baidu.com COM / Hello, only available at www.baidu.com Send ajax on the page of COM

How to process the received response

XMLHttpRequest provides several events, but only cares about the load event

oReq.addEventListener("load", reqListener);
oReq.onload = reqListener;

When the response is successful:

xhr.onload = function(){...}

xhr. Bind processing logic for XHR's load event before send()

xhr.onload = function() {
xhr.responseText;//Get response body
this.responseText;//Get response body
//xhr == this;
};


Advantages of JSON
In js, you can directly get js objects, arrays and other types of data through text in json format

JSON.parse(json text);//Parse JSON text to get js data

xhr.onload = function () { 
    var r = JSON.parse(this.responseText); 
    console.log(r); 
}

Array style

Combined with the function of modifying DOM + ajax of JS, we can use js to obtain data from the back end and modify the effect of page display!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>send out ajax</title>
</head>
<body>
  <table border="1">
      <thead>
          <tr>
              <th>ID</th>
              <th>full name</th>
              <th>Age</th>
          </tr>
      </thead>
      <tbody>

      </tbody>
  </table>

  <script>
      var tbody=document.querySelector("tbody");
      alert("Next, initiate a request to the backend");
      //Ready to send get / user list JSON request
      var xhr=new XMLHttpRequest();
      xhr.open("GET","/user-list.json");
      xhr.onload=function(){
          alert("The server responded successfully. Next, modify DOM structure");
          var userList=JSON.parse(this.responseText);
          console.log(userList);

          //Traverse userList
          for(var i in userList){
              var user=userList[i];
              console.log(user);
              alert("Click to add a new user to table in");

              //When you modify the DOM tree, the browser is not guaranteed to see the modification immediately
              var html=`<tr><td>${user.uid}</td><td>${user.name}</td><td>${user.age}</td></tr>`
              tbody.innerHTML+=html;
          }
          alert("All users have been added to table In, the utilization is realized js Effect of dynamically generating web content");
      }
      xhr.send();
  </script>
</body>
</html>




Front and rear end separation

  • Front end and back end separation: a technical scheme for separating responsibilities between the front end and the back end with HTTP protocol as the data carrier and JSON as the data format! (the current popular technical scheme of front and rear end separation, more than 90% of the products are made in the front and rear end mode)

  • Because the front-end logic has become responsible, there are many frameworks in the front-end to reduce the application complexity, such as vue
    The back end basically degenerates into a role similar to the database management system, which is only responsible for providing functions such as permission verification, data addition, deletion, query and modification

  • Developing a large-scale product requires the cooperation of many people. For example, a medium-sized project requires 5-10 people
    In the early scheme, the back end is responsible for generating HTML content and needs to complete basic js operations (5-10 people need to learn HTML, css, js and java)
    Front end and back end separation scheme: the back end is responsible for providing data, and the front end is responsible for obtaining and displaying data
    [front end group (5 people)]: html, css, js, http
    [back end group (5 people)]: java, http

Sending data back through ajax

Send data in JSON format

give an example:

  <script>
      var data={
          id:999,
          name:"Go, go, go",
          age:19
      };
      //Serialize the data in js into text format
      dataStr=JSON.stringify(data);
      var xhr=new XMLHttpRequest();
      xhr.open("post","/submit-json");
      xhr.setRequestHeader("Content-Type","application/json");//The format of the request body is JSON
      xhr.send(dataStr);//Send the dataStr as the response body
  </script>

In java, all peripheral data sources (non memory data) are abstracted into input streams

Redirect of response

Direct (specify direction), redirection is also called jump (behavior from the browser)

Conceptual classification of redirection:

  1. Temporary redirection (buy cabbages. Cabbages haven't been available recently. They won't be available until 3 or 5 days later. Recently, buy spinach first)
  2. Permanent redirection (buy Stone, because of the change of name, you should always buy a dream of Red Mansions in the future)

Retain method:

  1. Redirection of reserved methods
  2. Redirection of methods is not preserved

How the HTTP protocol implements redirection:
Through the status code (3XX) + response header (Location: reset the backward resource URL)

3xx = > distinction: permanent vs temporary, reserved vs not reserved

  • When requesting post resources, users need to log in first
    When the user does not log in, redirect to the login page
    When the user logs in successfully, redirect to the home page

Topics: Javascript JSON Ajax