AJAX(Async JavaScript and XML) refers to the asynchronous communication of JavaScript to extract data from an XML document from a server and then update the corresponding portion of the current web page without refreshing the entire web page. Later, the term AJAX became synonymous with HTTP communication initiated by JavaScript scripts, meaning that any communication initiated by a script could be called AJAX communication. The W3C also published its international standard in 2006.

How to make a request?

The browser communicates with the server over HTTP. When a user types a web address into the browser’s address bar or submits content to the server through a web form, the browser makes an HTTP request to the server.

There are other ways we can send requests.

<form>The label

You can make a request with a form, but it refreshes or opens a new page

<form action="x" method=post>
  <input type="username" name="username">
  <input type="submit">
</form>
Copy the code

When the submit button is clicked, a POST request is made (set the request type in the Method section of the form).

Username =123 (usernam is set in the name of the first input tag, and the following class is the content of the input field).

< a > tag

Use A to send get requests, but also refresh or open new pages

<a href="x">Click on the</a>
Copy the code

When the button is clicked, a GET request is made.

The < img > tag

Img allows you to send get requests, but only in the form of images

<script>
  var image = document.createElement('img')
  image.src = '/x'
  document.body.appendChild(image)
</script>
Copy the code

When an IMG tag is defined and the SRC path is set, a GET request is made. When the IMG tag is introduced into the page, it can only be displayed as an image

The < link > tag

Link allows you to send get requests, but only in the form of CSS and Favicon

<script>
  var link = document.createElement('link')
  link.rel = 'stylesheet'
  link.href = '/x'
  document.head.appendChild(link)
</script>
Copy the code

The link tag will not make a request until it is defined and introduced to the page. (The IMG tag can make a request once it is defined.)

< script > tag

Get requests can be made with script, but they can only be executed as scripts

<script>
  var script = document.createElement('script')
  script.src = '/x'
  document.head.appendChild(script)
</script>
Copy the code

When a Script tag is defined and introduced to the page, a GET request is made

The advanced

Is there any way to do that

  • get,post,put,deleteThe request is ok
  • You can show it in whatever format you want

AJAX

Using AJAX, you can make HTTP requests to get data back from the server and then process it. Although the X for AJAX stands for XML, the server currently returns data in JSON format, and the AJAX literal meaning has been lost and has become a generic term.

Specifically, AJAX involves the following steps.

  • createXMLHttpRequestThe instance
  • aHTTPrequest
  • Receive data returned by the server
  • Update web data

An AJAX request

button.addEventListener("click", e => {
  let request = new XMLHttpRequest();
  request.open("GET"."/yyzcl"); / / configuration request
  request.setHeader("yyzcl"."OK"); // Set the request header
  request.send("Yyzcl");
  request.onreadystatechange = (a)= > {
    if (request.readyState === 4) {
      let string = request.responseText;  // Gets the return value of the server, which is a string
      let obj = window.JSON.parse(string);  // Convert JSON strings to JS values (objects, strings, etc.)}}; });Copy the code
  • Configure the requestopenIs used to configurerequest, a total of 5 parameters can be passed, let’s look at the interpretation of MDN.
void open(
   DOMString method,
   DOMString url,
   optional boolean async,
   optional DOMString user,
   optional DOMString password
);
Copy the code

The first parameter is the request mode, the second parameter is the request address, the following parameters generally do not change, use the default Settings, so generally set only two parameters.

  • The request statusreadyStateRepresents the state of the request, which has five states.
value state describe
0 UNSENT (not opened) The open() method has not yet been called.
1 OPENED (not sent) The open() method has been called.
2 HEADERS_RECEIVED (response header obtained) The send() method has been called, and the response header and response status have been returned.
3 LOADING (LOADING the response body) Response body downloading; ResponseText already got some data.
4 DONE (request completed) The entire request process is complete.

The second value provides additional information that the client downloads the response body in segments.

  • The request header setHeader is used to set the request header in the key:value format.

  • Request body Send is used to set the request body. It is a string.

AJAX parsing

Take a look at the previous AJAX request.

button.addEventListener("click", e => {
  let request = new XMLHttpRequest();
  request.open("GET"."/yyzcl");
  request.setHeader("yyzcl"."OK");
  request.send("Yyzcl");
  request.onreadystatechange = (a)= > {
    if (request.readyState === 4) {
      let string = request.responseText;
      let obj = window.JSON.parse(string); }}; });Copy the code
  • openIs used to set up the first part of the HTTP request
  • setHeaderIs used to set the second part of the request header, where some information is set automatically by the browser
  • sendIs used to set the fourth part of the request header,getThe request can also set part 4, which does not report errors, but this does not work

Response body analysis

Request. status and request.statusText are the first part of the response body

Request. The getAllResponseHeaders () or request. The getResponseHeader () is the second part of the response body

ResponseText is the fourth part of the response body

AJAX’s same-origin policy

AJAX can only make HTTP requests to same-origin urls (the same protocol, domain name, and port), and if it makes cross-domain requests, an error will be reported

Such as:

https://www.github.com cannot send AJAX requests to http://www.github.com

http://github.com cannot send AJAX requests to http://www.github.com

http://www.github.com:80 cannot send AJAX requests to http://www.github.com:81

CORS

CORS is a W3C standard, which stands for cross-origin Resource Sharing. It allows browsers to issue XMLHttpRequest requests across source servers, overcoming the limitation that AJAX can only be used in the same source.

If A wants to use JavaScript to send an AJAX request to B’s website, all it needs to do is write on B’s back end: Response.setheader (‘ access-Control-allow-Origin ‘,’ Origin’) response.setheader (‘ access-Control-allow-Origin ‘,’ Origin’)

You can implement AJAX cross-domain requests.

JSON

JSON (JavaScript Object Notation) is a lightweight data interchange language conceived and designed by Douglas Crockford. JSON is a subset of JavaScript, but it is a language-independent text format. And adopted some habits similar to the C language family.

JSON data formats include String, Number, Object, array, true, false, and NULL, which are somewhat different from JavaScript.

JavaScript JSON
undefined There is no
null null
[‘A’,’B’]/[“A”,”B”] [“A”,”B”]
function fn(){} There is no
{name: ‘yyzcl’/”yyzcl”} {“name”: “yyzcl”}
‘yyzcl’/”yyzcl” “yyzcl”
var a={} JSON has no variables
{proto} JSON has no prototype chain