Front End Summary, Foundation Chapter, JS (IV) Asynchronous Request and Cross-domain Solutions

Front end summary series

Catalog

I. Asynchronous requests
    1.1 XHR(XMLHttpRequest)
    1.2 Promise(ES6)
    1.3 Fetch

II. Cross-domain solutions
    2.1 JSONP(JavaScript Object Notation with Padding)
    2.2 CORS(Cross-origin resource sharing)

I. Asynchronous requests

This article only gives a brief introduction. See me for a complete use case. Github . Use cases on Github encapsulate POST and GET requests for all three methods.

The Github demo does not support POST requests, so there will be some errors. The complete test can be placed under the local host of the machine.

a.json
-------------
{
"user":"Zhang San",
"folling":30,
"foller": 20
}

1.1 XHR(XMLHttpRequest)

Three lines of code to implement asynchronous requests

Following is the success message returned after sending the XHR request.

<script type="text/javascript">
  var xmlhttp = new XMLHttpRequest()  // Create asynchronous requests
  xmlhttp.open('GET','a.json')  // Get the hello.txt file using GET method
  xmlhttp.send()  // Send asynchronous requests
</script>

Read the data returned by the asynchronous request

The returned data is stored in xmlhttp.responseText.

How did you return so much? Look down, please.

<script type="text/javascript">
  var xmlhttp = new XMLHttpRequest()
  // This function is executed when the asynchronous request state changes
  xmlhttp.onreadystatechange = function () {
    // Display the returned content
    console.log(xmlhttp.responseText)
  }
  xmlhttp.open('GET','hello.txt')
  xmlhttp.send()
</script>

Status of asynchronous requests

Now that's it, let's take a look at the current status of ajax before using xmlhttp.responseText. Confirmation is complete, and we return the value.

<script type="text/javascript">
  var xmlhttp = new XMLHttpRequest()
  xmlhttp.onreadystatechange = function () {
    // Status = 200 is used to determine the completion of the current HTTP request
    if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
      console.log(xmlhttp.responseText)
    }
  }
  xmlhttp.open('GET','hello.txt')
  xmlhttp.send()
</script>

There are five states for asynchronous requests, which are used to identify different stages of asynchronous requests.

  • 0 UNSENT agent was created, but the open() method has not yet been invoked
  • 1 OPENED open() method has been called
  • 2 HEADERS_RECEIVED send() method has been called, and the header and state are available
  • 3 LOADING Download; the responseText attribute already contains some data
  • 4 DONE Download Operation Completed

One of the five data returned above is the successful default return of the XHR request. The first two corresponding states 1 and 2 do not return content, so they are empty. The latter two contents correspond to 3 and 4.

Therefore, we want the data to be downloaded completely before the return content is displayed. We just need to use if to determine whether the current status is 4 or not.

For the meaning of HTTP status codes, see what I've written before. Article.

Encapsulation XHR Method

function ajax (method,url,callback) {
  var xmlhttp = new XMLHttpRequest()  // Create asynchronous requests
  // This function is executed when the asynchronous request state changes
  xmlhttp.onreadystatechange = function () {
    // Status = 200 is used to determine the completion of the current HTTP request
    if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
      callback(JSON.parse(xmlhttp.responseText))  // CCCallFuncN
    }
  }
  xmlhttp.open(method,url)  // Getting by GET method
  xmlhttp.send()  // Send asynchronous requests
}

Call the XHR method

ajax('GET','a.json',function (res) {
  console.log(res)  // Display the returned object
  ajax('GET','b.json',function (res) {
    console.log(res)
    ajax('GET','c.json',function (res) {
      console.log(res)
    })
  })
})

1.2 Promise(ES6)

When we write asynchrony in Ajax, it's easy to fall into callback hell, and the readability of the code will be greatly reduced. Promise can make code more elegant.

Encapsulation of Promise-based XHR

function ajax ( method,url ) {
  // Returns a Promise object
  return new Promise(function (resolve) {
    var xmlhttp = new XMLHttpRequest()  // Create asynchronous requests
    // This function is executed when the asynchronous request state changes
    xmlhttp.onreadystatechange = function () {
      // Status = 200 is used to determine the completion of the current HTTP request
      if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
        resolve(JSON.parse(xmlhttp.responseText))  // Markup completed
      }
    }
    xmlhttp.open(method,url)  // Getting by GET method
    xmlhttp.send()  // Send asynchronous requests 
  })
}

Calling Promise-based XHR

var aj = ajax('GET','a.json')
aj.then(function (res) {
  console.log(res)
})

1.3 fetch

fetch is an encapsulation of Promise, which is very convenient to use.

fetch('a.json').then(function (res){
   return res
}).then(function (res) {
   return res.json()
}).then(function (json) {
   console.log(json)
})

II. Cross-domain solutions

CORS is better, but it requires autonomy on the server. JSONP does not need to have autonomy over the server. It can send GET requests through script, img and other tags, and execute existing JS functions through callback functions. Gets the return value in the function.

CORS supports all HTTP requests and JSONP only supports GET requests.

2.1 JSONP(JavaScript Object Notation with Padding)

Using callbacks across domains
------------------------
<script type="text/javascript" src="http://localhost/async/cors.php?callback=go"></script>

Setting up callback function
------------------------
function go (arr) {
  console.log(arr)// Displays the value of the callback | {a:"1"}
}

When a GET request is sent by script, the value returned is a function, and the callback function is executed.
------------------------
<?php 
$go=$_GET['callback']; // Gets the value of callback
 echo $go.'({a:"1"});// output callback function
?>


2.2 CORS(Cross-origin resource sharing)

PHP Configuration CORS

<?php 
header("Access-Control-Allow-Origin:*");
?>

Before configuring CORS

After configuring CORS

summary

The next article summarizes Vue.

Reference resources

Keywords: Javascript JSON PHP github

Added by prakash on Sun, 14 Jul 2019 01:44:14 +0300