The preparatory work

Tools:

  • VS Code
  • Postman

Initialization: Create a file page first

1, the json – server

1.1 json – server is introduced

A server that runs locally on the front end and stores JSON data: it can simulate requests and requests back

1.2 the use of

1. Use it in the page directorynpm init -yThe initialization project is now generated in the Page directory

2, continue to usenpm i json-serverThe installationjson-serverThe page directory becomes:

3, create a new db.json file under the page file to store the data we need and change the data in the db. Json file to your own:

{
  "users": [{"name": "jinda1"."id": 1
    },
    {
      "name": "jinda2"."id": 2
    },
    {
      "name": "jinda3"."id": 3}}]Copy the code

So what we need to think about is, how do we start jSON-server to fully simulate the request and the request back

Modify the value of “scripts” to create a command line to start db.json as the background data source

 "scripts": {
   "server:json":"json-server --watch db.json"
  },
 // Or choose your own port
  "scripts": {
   "server:json":"json-server --watch --port 1234 db.json"
Copy the code

NPM run server:jsonAt this point you have successfully started jSON-server

Let’s say the back end is ready, and then how does the front end request this back end data that we created

2. Add data using postman

The first thing to be clear about is

  • In the web browser using HTTP and server side request to read data is GEThttp://localhost:3000/usersIt’s going to get an arrayusers[]
  • A POST request is usually sent via an HTML form and returns the server’s modification results

At this point we can use the Postman tool that we talked about earlier, throughhttp://localhost:3000/usersThis interface is used to add db. Json dataAdd key and value values to the body interface:After sending, you can return to db.json to check whether the data was added successfully:

XMLHttpRequest requests data

3.1 the XMLHttpRequest is introduced

The XMLHttpRequest (XHR) object is used to interact with the server. With XMLHttpRequest, you can request a specific URL to retrieve data without refreshing the page. This allows the web page to update parts of the page without affecting the user’s actions.

3.1.1 XMLHttpRequest() constructor

XMLHttpRequest() This constructor is used to initialize an XMLHttpRequest instance object. The constructor must be called, or otherwise, to get an instance object on this object before any of the following other methods can be called

Let’s start with some of the methods we’ll be using:

  • XMLHttpRequest.onreadystatechange

When the readyState property changes

  • XMLHttpRequest.readyState Read-only returns an unsigned short number representing the requested status code

There are the following states:

0: the corresponding XMLHttprequest.unsent is not initialized

1: xmlHttprequest. OPENED is being loaded

2: xmlHttprequest. HEADERS_RECEIVED

3: xmlHttprequest.loading is being processed

4: Indicates that xmlHttprequest. DONE is displayed

  • XMLHttpRequest.responseText read-only

Returns a DOMString containing the response to the request, or null if the request was unsuccessful or not yet sent.

3.2 Usage

3.2.1 The GET method is used to obtain data

Create a new index. HTML file in the page directory, which is used to retrieve users data, and display it on the page as follows:

  • Create a div tag with id attribute users

  • Use document.getelementByID to take this element and assign it to oUsers, and add the data obtained later to its contents

  • HttpRequest = new XMLHttpRequest(); Create an instance of XMLHttpRequest().

  • When the readyState attribute changes, method call httpRequest. The onreadystatechange

  • Httprequest. readyState == XMLHttprequest. DONE is completed

  • Go to the front end to get the data

 let users = JSON.parse(httpRequest.responseText);
Copy the code
  • Add the obtained data to oUsers,
oUsers.innerHTML = users.map( user= >  
<li>${user.id} - ${user.name}
<li>`).join('')
Copy the code
  • httpRequest.open(“GET”,”http://localhost:3000/users”,true); Initialize HTTP request parameters

  • httpRequest.send(); Making an HTTP request

Complete code:

<body>
  <div id="users"></div>
  <script>
    const oUsers = document.getElementById('users');
    let httpRequest;
    if(window.XMLHttpRequest) {
    </user>
      httpRequest = new XMLHttpRequest();// Data request instance XHR
    } else if(window.ActiveXObject) {
      httpRequest = new ActiveXObject('XMLHTTP');
    }
    httpRequest.onreadystatechange = function () {
      if(httpRequest.readyState == XMLHttpRequest.DONE) {
        let users = JSON.parse(httpRequest.responseText);
        oUsers.innerHTML = users.map( user= > `
        <li>${user.id} - ${user.name}<li>
        `).join(' ')
      }
    }
    httpRequest.open("GET"."http://localhost:3000/users".true); 
    httpRequest.send();

  </script>
</body>
Copy the code

In the front http://127.0.0.1:8080/ you can see the requested data and display it on the page:

Of course, you can also see in Network that the requested address is what we originally wrote"http://localhost:3000/users"

3.2.2 Post Method: Send data to the server.

Create a new add.html file in the Page directory:

In the example above one more method: XMLHttpRequest. SetRequestHeader () sets the value of the HTTP request header. Note that the setRequestHeader() method must be called after open() but before send().

<body>
  <script>
  const xhr = new XMLHttpRequest();
  let name = 'post';
  xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE) {
      console.log('Saved successfully')
    }
  }
  xhr.open('POST'.'http://localhost:3000/users'); // Create a link
  // Set the request header
  xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
  xhr.send('name=' + encodeURIComponent(name));
  </script>
</body>
Copy the code

Run this code in thedb.json,http://localhost:3000/usersAs well ashttp://127.0.0.1:8080/Will addName = "post"

So we get to post the data to the server, and with the back-end data in front of us, we get the data by accessing the db.json file and displaying it on the page

conclusion

As you can see, jSON-Server works with XMLHttpRequest to communicate data, whether it’s a get request from the browser (front end) or a POST request to the server for display on the page. XMLHttpRequest brings the ability of the front end to actively request data, making the front end page richer and more dynamic.