Only by knowing the history can we better grasp the present and the future.

In the project, usually front-end development mainly completes two things, one is the interface construction, the other is the data interaction.

The following are some of the ways I summarize front-end and back-end interactions, but I won’t go into depth in this article.

A, AJAX

The paper

AJAX (Asynchronous Javascript And XML) is a programming practice for building more complex, dynamic web pages using XMLHttpRequest technology.

The XMLHttpRequest (XHR) object, introduced by Microsoft and first implemented in IE5, is a technology that supports asynchronous requests to interact with the server. XMLHttpRequest can request a URL to fetch server data without refreshing the page, and then use JavaScript to manipulate the DOM to update the page data, which is the core of AJAX programming techniques. In this way, the local content of the page can be updated without affecting the user’s operation, and the user experience has been greatly improved. Previously, such Ajax-style communication was achieved through hacks such as embedded or hidden frameworks.

In addition to native JS, jQuery, Axios, and Vue-Resource can all implement Ajax programming.


Native JS

var url = 'https://api.github.com/users/chriscoyier/repos'
var xhr = new XMLHttpRequest()
xhr.open('GET', url, false)
xhr.onreadystatechange = function() {
  if(xhr.readyState === 4) {
    if(xhr.status === 200 || xhr.status === 304) {
      console.log('response:', xhr.response)
    }
  }
}
xhr.send()
Copy the code

encapsulated

var Ajax = {
    get: function(url, callback) {
        var xhr = new XMLHttpRequest()
        xhr.open('GET', url, false)
        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4) {
                if(xhr.status === 200 || xhr.status === 304) {
                    console.log(xhr.response)
                    callback(xhr.response)
                }
            }
        }
        xhr.send()
    },

    post: function(url, data, callback) {
        var xhr = new XMLHttpRequest()
        xhr.open('POST', url, false)
        xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded')
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if (xhr.status === 200 || xhr.status === 304) {
                    console.log(xhr.response)
                    callback(xhr.response)
                }
            }
        }
        xhr.send(data)
    }
}
Copy the code

jQuery

Implementing Ajax under jQuery is very simple

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
  $(function(){
      const list = {}
      const url = ' '
      $.ajax({
          type: "POST".contentType: "application/json; charset=UTF-8".url: url,
          data: JSON.stringify(list),
          success: res= > console.log('res', res),
          error: err= > console.log('err', err)
      })
  })
</script>
Copy the code

vue-resource

Vue-resource is a plug-in for vuejs, widely used in vu1.x, to send requests and process response data using XMLHttpRequest or JSONP.

Vue-resource’s ability to send requests for data through JSONP means it supports cross-domain access

Install using NPM or YARN

$ yarn add vue-resource
$ npm install vue-resource
Copy the code

Import through CDN

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
Copy the code

use

this.$http.get('https://api.github.com/users/chriscoyier/repos')
        .then(res= > console.log('res:', res.body),err= > console.log('err:', err))
Copy the code

Axios

Axios, available in browsers and Node.js, is a Promise based HTTP library and is recommended on vuejs’ website.

The use of NPM

$ npm install axios
Copy the code

Use the bower

$ bower install axios
Copy the code

Use the CDN

// Synchronize the latest version, but it is not recommended to use, may cause access problems
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
// It is recommended to use the specified version
<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>
Copy the code

Complete the request

axios.get('https://api.github.com/users/chriscoyier/repos')
          .then(res= > console.log('res:', res.data),err= > console.log('err:', err))
Copy the code

Promise

Use ES6’s Promise to complete the Get request

const url = 'https://api.github.com/users/chriscoyier/repos'
const getData = function(url) {
  const promise = new Promise(function(resolve, reject) {
      const handler = function() {
          if (this.readyState ! = =4) {
              return
          }
          if (this.status === 200) {
              resolve(this.response)
          } else {
              reject(new Error(this.statusText))
          }
      }
      const xhr = new XMLHttpRequest()
      xhr.open("GET", url)
      xhr.onreadystatechange = handler
      xhr.responseType = "json"
      xhr.setRequestHeader("Accept"."application/json")
      xhr.send()

  })
  return promise
}
getData(url)
  .then(res= > console.log('data: ', res), err= > console.log('err: ', err))
Copy the code

Second, the Fetch

Introduction to the

Fetch is based on Promise and provides an interface to Fetch resources (including cross-domain requests). Its global method fetch() requires that a resource path must be received, and whether the request succeeds or fails, it returns a Promise object, resolve corresponding to the Response of the request. It is more efficient and extensible than XMLHttpRequest.

The core of Fetch lies in the abstraction of HTTP interfaces, including Request, Response, Headers, Body, and global Fetch for initiating asynchronous requests.

Using the Fetch

fetch('https://api.github.com/users/chriscoyier/repos')
  .then(res= > res.json())
  .then(res= > {
    console.log('res', res[0].blobs_url)
  })
Copy the code

Third, the WebSocket

Introduction to the

WebSocket is a web protocol provided by HTML5 for full two-way communication over a single TCP connection. It was released in 2008 and was supported by all browsers in 2011. Its appearance makes up for the defect that HTTP protocol can only be initiated by the client to the server. Before that, Ajax polling was the only way to push data from the server to the client, that is, every once in a while, a request would be sent to ask the server if there is any new message, which resulted in HTTP being open all the time, which was very inefficient, so engineers invented WebSocket. In the WebSocket API, the browser and server only need to complete a handshake to create a persistent connection and two-way data transfer.

The following is a WebSocket protocol. Ws represents the protocol, and WSS represents the encryption form of WS. Port and HTTP maintain good compatibility, also 80/443, but there is no HTTP origin limit, can arbitrarily communicate with the server.

ws://example.com:80/some/path
Copy the code

Client-side implementation

An example of a web script


// After executing the following statement, the client will connect to the server.
var ws = new WebSocket("wss://echo.websocket.org");

ws.onopen = function(evt) { 
  console.log("Connection open ..."); 
  ws.send("Hello WebSockets!");
};

ws.onmessage = function(evt) {
  console.log( "Received Message: " + evt.data);
  ws.close();
};

ws.onclose = function(evt) {
  console.log("Connection closed.");
};      

Copy the code

4

A Form is an element in HTML that represents an area of a document and typically has many child elements that provide an interactive role in providing data to a Web server.

<form action="" method="get" class="form-example">
  <div class="form-example">
    <label for="name">Enter your name: </label>
    <input type="text" name="name" id="name" required>
  </div>
  <div class="form-example">
    <label for="email">Enter your email: </label>
    <input type="email" name="email" id="email" required>
  </div>
  <div class="form-example">
    <input type="submit" value="Subscribe!">
  </div>
</form>

Copy the code

Action represents the URL to process the form submission. This value can be overridden by the formAction attribute on the

Reference documentation

developer.mozilla.org/zh-CN/

Jquery. Cuishifeng. Cn/jquery Ajax…

Github.com/pagekit/vue…

www.axios-js.com

www.ruanyifeng.com/blog/2017/0…

Developer.mozilla.org/zh-CN/docs/…