Note: This is the summary content made during the learning of relevant courses, which has not been practiced. If you want to learn more vividly, you can watch the relevant video of STATION B

An overview of the

It is a set of methods provided by the browser, which can realize the page without updating data, and improve the application experience of the user browsing the website

Users can partially refresh the page while browsing the web page

Application Scenarios:

  1. More data is pulled and loaded on the page
  2. There is no refresh page for list data
  3. The one under the form that is out of focus data validation
  4. Search box prompts text drop – down list

Note: need to run in the website environment to take effect

Operation and principle realization

Creating Ajax objects

  1. create

    var xhr = new XMLHttpRequest();
    Copy the code
  2. Tell Ajax where and how to make the request

    Tell Ajax where to send the request, and how

    xhr.open('get'.'http://www.example.com');
    Copy the code

    This address is actually the routing address of the server

  3. Send the request

    xhr.send();
    Copy the code
  4. Gets response data from the server to the client

    xhr.onload = function () {
      console.log(xhr.responseText);
    }
    Copy the code

When Ajax receives the response from the server, the onLoad event is triggered

In a real project, the server-side will most likely take JSON objects as the format for the response data. When the client gets the response data, it concatenates the JSON data with the HTML string and displays the concatenated result on the page.

In the process of HTTP request and response, both request parameters and response contents, if they are object types, will eventually be converted into object strings for transmission

JSON.parse();    // Convert the js string to a JSON object
Copy the code

Pass request parameters

In the traditional form, requests are delivered via a form. As soon as the form is submitted, the content of the form becomes the request parameters and is automatically concatenated to the corresponding position, depending on the request method. The GET request is concatenated to the address of the request, and the POST request is placed in the body of the request. However, in either case, the request parameters are in the form of “request name = parameter value”, and multiple parameters are connected by ampersand (&).

In Ajax, you want to concatenate the request parameters and put them in their respective positions depending on how the request is made.

The get method:

xhr.open('get'.'http://example.com?name=zhangsan&age=18');
Copy the code

Post:

xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
xhr.send('name=zhangsan&age=20');
Copy the code

The parameters are directly placed in the SEND method. However, it is important to note that the Content Type of the request parameters, namely the content-Type attribute, must be explicitly set in the POST request message

Request parameter format

  1. The content-type attribute values are Application/X-www-form-urlencoded

    name=zhangsan&age=20
    Copy the code
  2. The content-type attribute value is Application /json

    {name: 'zhangsan'.age: 20}
    Copy the code

    Note that we need to convert JSON to a string format and put it in the SEND method

    JSON.stringify()// Convert a JSON object to a JSON string
    Copy the code

    BodyParser in the server also needs to be reconfigured, for example

    app.use(bodyParser.json());   // Accept json parameters
    Copy the code

Note: GET requests do not submit JSON object data format, nor do traditional web site form submissions support JSON object data format

Ajex status code

The procedure state representing the Ajax request is returned by the Ajax object

onreadystatechangeThe event that listens for changes in the status code is added before the request is sent, before the send method

Ajax error handling

  1. Case 1: The server can receive the request when the network is normal, but the return result is not the expected result

    Solution: Determine the status code returned by the server and process it separately

    xhr.status  // Get the HTTP status code
    Copy the code
  2. Case 2: The network is normal. The server does not receive the request and returns the 404 status code

    Handling method: Check whether the request address is wrong

  3. Case 3: The network is normal, the server can receive the request, and the server returns the 500 status code

    Solution: Talk to a back-end programmer

  4. Case 4: The network is interrupted and the request cannot be sent to the server

    Handling method: The onError event under XHR object will be triggered, and the error will be processed in the onError event handler function

    xhr.onerror = funcion (){
      alert('Network interruption');
    }
    Copy the code

The cache of Internet Explorer of earlier versions is abnormal

In earlier versions of Internet Explorer, Ajax requests have serious caching problems. If the address of the request does not change, only the first request is actually sent to the server, and subsequent requests are retrieved from the browser’s cache. Even if the data on the server is updated, the client still gets the old data.

Solution: Add one request parameter after the request address to ensure that the value of the request parameter is different in each request

xhr.open('get'.'http://example.com?t=' + Math.random);
Copy the code

Ajax asynchronous programming

Synchronous and asynchronous

Synchrony: a person can only do one thing at a time, only when one thing is done, can do another thing; The implementation of code is that one line of code can be executed before the next line of code is executed, that is, the code is executed line by line.

Asynchrony: when a person does one thing in general, he or she moves on to another, and when the other things are done, he or she goes back to the unfinished work. The implementation of the code is that the asynchronous code takes time to execute, but the program does not wait for the completion of the asynchronous code to continue to execute the following code. Instead, the program directly executes the following code, and then checks the return result of the asynchronous code after the completion of the code execution. If there is a return result, The prepared callback function is called to process the result of asynchronous code execution.

The process of sending Ajax requests is the process of executing asynchronous code;

Ajax encapsulation

  1. Setting parameters as objects helps us better understand what each parameter represents.
  2. Passing object data types is friendlier to function callers and easier to convert object data types to string data types inside functions.
  3. When the onLoad event is triggered, it only indicates that the request is completed, but does not necessarily mean that the request is successful. Therefore, you need to determine the HTTP status code.
  4. Processing server return value, when the server returns the data, will set the data return type in the response header, we can judge the data type in the response header; Gets the data in the response headerxhr.getReponseHeader;
  5. An Ajax function with too many parameters can cause problems for the caller, so we can set default values for some parameters and let the caller pass only the necessary parameters
function ajax (options){
  // Set the default object
  var defaults = {
    type: 'get'.url: ' '.data: {},
    header: {'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function(){},
    error: function(){}}// Override the default object
  Object.assign(defaults,options);
  // Create Ajax objects
  var xhr = new XMLHttpRequest();
  var params = ' ';
  // Convert the format of the passed argument to a string format
  for(var attr in defaults.data) {
    params += attr + '=' + defaults.data[attr] + '&';
  }
  // Intercepts the last ampersand
  params.substr(0,params.length - 1);
  
  // Determine the request type
  if (defaults.type == get){
    defaults.url += '? ' + params;
  }
  
  // Configure the Ajax object
  xhr.open(defaults.type,defaults.url);
  
  if (defaults.type == post){
      // Send the request
    var contentType = defaults.header['Content-Type']
    xhr.setRuquestHeader('Content-Type',contentType);
    // Determine what type of request parameter format the user wants
    // If it is Json
		if(contentType == 'application/json') {// Return data in Json format to the server
       		xhr.send(JSON.Stringify(defaults.data));
    }else{
      // If not, pass the normal type parameter to the serverxhr.send(params); }}else{
    xhr.send();
  }

  // Listen for the onload event in the XHR object, which is triggered when the object receives the response data
  
  
  xhr.onload = function(){
    
    // Determine the type of data returned
    var contentType = xhr.getReponseHeader('Content-Type');varThe responseText = XHR. The responseText;// If it is JSON, further conversion is required
    if(contentType.includes('application/json') {// Convert a JSON string to a JSON object
       responseText = JSON.parse(responseText)
    } 
    // When the HTTP status code is 200, the request is successful and the code is successfully invoked
    if(xhr.atutas == 200){
      defaults.success(responseText,xhr);
    }else{
      // Otherwise, the request fails and the code fails to be invoked
      defaults.error(responseText,xhr);
    }
  } 
}

ajax ({
  url: 'http://www.example.com'.data: {
    name: 'zhangsan'.age: 20
  },
  success: function(data,xhr){
    console.log(data);
  },
  error: function(The data, XHR){
    console.log(data); }})Copy the code

A template engine

What it does: Concatenates data with HTML using the syntax provided by the template engine

The official address

FromData object

Function and use method

Function:

  1. Emulating AN HTML form is equivalent to mapping an HTML form to a form object, and automatically stitching the data in the object in the form into the format of the request parameters.
  2. Asynchronously upload binary files (such as pictures and videos)

Create the formData object

var form  = document.getElementById('form');
var formData = new FormData(form);
Copy the code

Submit form object

xhr.send(formData);
Copy the code

Note: You cannot use the GET method for the request because the formData object content is placed in the send method.

This is what Html5 provides, and there are compatibility issues

Instance methods

These methods are all operations on the data in the form. Generally speaking, the form data will not be directly called to the server side by I. After the user clicks the submit button, the client side generally needs to verify the data.

  1. Gets the value of an attribute in the form object

    formData.get('key');  // Key represents the value of the name property in the form control
    Copy the code
  2. Sets the property values of the form control

    formData.set('key'.'value'); 
    Copy the code

    Note: if the value of the form attribute exists, it will be replaced with the original value; If the property does not already exist in the form, it will be created.

  3. Deletes the attribute value of the form object

    For example, some of our forms will enter passwords twice, so we only need to submit one and delete one

    formData.delete('key');
    Copy the code
  4. Appends values to the form object

    Application scenario: We can also create an empty form object while creating the formData object and append it

    formData.append('key'.'value'); 
    Copy the code

    Note that both the set and Append methods can append attributes to the form object, but the difference is that the set method overwrites the existing value if the attribute name already exists, while the Append method keeps both values, but it defaults to the last value unless the server makes a special setting.

Binary file upload

Ajax request restrictions

Ajax cannot send requests to non-same-origin addresses; Ajax can only send requests to its own server. If the client sends a request to a non-cognate site, the browser’s controls would be too bad. In fact, the request can be sent, but the browser refuses to receive the result from the server, and the seat fails.

homologous

Multiple requests or pages come from the same server.

If two pages have the same protocol, domain name, or port, the two pages belong to the same source. If one page is different, it is a different source.

The same-origin policy

The same-origin policy ensures user information security and prevents malicious websites from stealing data. The original same-origin policy refers to the cookies of website A, and website B is not accessible.

Resolve homologous restriction

The json to solve

Use JSONP to solve the same-origin restriction problem (it’s not really Ajax requests anymore, but you can simulate the effect of Ajax requests by bypassing the browser’s same-origin policy and sending requests to non-same-origin pages)

JSONP: json with padding

First, write the different source server request addresses in the SRC attribute of the script tag

<script src="www.example.com"> </script>
Copy the code

On the client side, not all of the ways in which requests can be sent are subject to the same origin policy, SRC being one of them.

After that, the response data on the server side must be a function call, and the data actually sent to the client needs to be the parameter of the function call

const data = 'fn({name: 'zhangsan', age: 20})';
res.send(data);
Copy the code

Define the function to be called in the client’s global scope, and write it before the script tag.

function fn (data){}
Copy the code

Finally, the data returned by the server is processed inside the function

function fn (data) {console.log(data)};
Copy the code

JSONP code optimization

  1. Solve the problem of sending a request as soon as the page is loaded, so that the request can be sent according to the user’s needs, such as clicking a button to dynamically send a request;

Method: Create a Script tag dynamically with JS

btn.onclick = function (){
  // Create the script tag
  var script = document.createElement('script');
  // Set the SRC attribute
  script.src = 'http://www.example.com';
  // Append to the page
  document.body.appendChild(script);
  // Add the onload event to the script tag
  script.onload = function (){
    // When the script is executed, delete the tag to avoid the phenomenon of multiple script tags in the page due to multiple clicks
    document.body.removeChild(script); }}Copy the code
  1. The client needs to pass the function name to the server so that the client can change the function name without affecting the server
<script src="www.example.com?callback=fname"> </script>
Copy the code
  1. Encapsulate JSONP functions
function jsonp (options) {
  // Dynamically create script tags
  var script = document.createElement('script');
  
  var params = ' ';
  for(var attr in options.data){
    params += '&' + attr + '=' + options.data[attr];
  }
  // Randomly generate a function name
  var fnName = 'myjsonp' + Math.random().toString().replace('. '.' ');
  // Make the passed function global
  window[fnName] = options.success;
  // Add the SRC attribute
  script.src = options.url + '? callback=' + fnName + params;
  // Append to the page
  document.body.appendChild(script);
  script.onload = function (){
    document.body.removeChild(script);
  } 
}

jsonp ({
  data: {name: 'lisi'.age: 30
  },
  url:'http://www.example.com'.success: function(data){
    console.log(data); }})Copy the code

Server-side optimization

app.get('/xxxx'.(req,res) = >{
  res.jsonp({name: 'lisi'.age: 20});
})
Copy the code

CORS cross-domain resource sharing

Full name: Cross-Origin Resourse Sharing, which allows browsers to send Ajax requests to cross-domain servers, overcoming the limitation that Ajax can only be used in the same source.

Simply put, if the server allows you to access it across domains, you can access it across domains; If the server doesn’t allow you to access it across domains, you can’t access it.

On the server: 1. Set the clients that can access the server. 2. Set which request methods are allowed to access

app.use((req,res,next) = > {
  res.header('Access-Control-Allow-Origin'.The '*');
  res.header('Access-Control-Allow-Origin'.'get,post')
  next();
})
Copy the code

The same-origin policy

Cookies to review

In THE HTTP protocol, the interaction between the client and the server is stateless, and no one knows who. For example, to realize the login function and identify the identity of the client, there is a cookie at this time, which is used to identify the identity of the client and server. Application up to, and for the first time when the client access to the server, the server will send an id card to the client, in response to a cookie, when the second time the client access server, the id card together with the request sent to the server, the server will know who is this client, it established a lasting connection.

Methods in jQuery

&.ajax()methods

Note:

Data can also pass concatenated strings

{
  data: 'name=zhangsan&age=20'
}
Copy the code

If the protocol, domain name, and port are the same when writing the requested address. Can be omitted

Serialize method

What it does: Automatically concatenates data in a form into string parameters

var params = $('#form').serialize()
//name=zhangsan&age=20
Copy the code

function serializeObject(obj) {
  // Process the result object
  var result = {};
  
  [{name:'username',value: 'zhangsan'},{name:'password',value: '12345']
  var params = obj.serializeArray();
  // Loop through the data to convert the array to an object type
  $.each(params,function(index, value){
    result[value.name] = value.value;
  })
  return result;
}
Copy the code

Send the JSONP request

$.ajax({
  url:... .dataType: 'jsonp'.// Optional, modify the name of the callback parameter
  jsonp: 'cb'.// Specifies the function name
  jsonCallback: 'fnName'.success: function(response){}})Copy the code


. g e t ( ) , .get (),
Post () method

Used to send GET and POST requests, respectively

$.get('http://www.example.com',{name; 'zhangsan'.age: 30},function(response){})

$.post('http://www.example.com',{name; 'zhangsan'.age: 30},function(response){})

// The second argument can be either an object or a string, and can be omitted if not required. The third argument is actually success
Copy the code

Global events in Jquery

Requirement: Whenever an Ajax request is sent on the page, the corresponding global event is triggered

.ajaxStart()  // Triggered when the request starts
.ajaxComplete() // Triggered when the request completes
Copy the code

Tell the user the progress, using the NProgress plug-in

RESTful apis

Disadvantages of traditional requests:

Semantic ambiguity and confusion, there is no unified specification to constrain

RESTful API Overview: A set of specifications for design requests

GET: Obtains data

POST: Adds data

PUT: Updates data

DELETE: deletes data

You don’t need to add a verb to the request address

Features: the request address is the same, the request way is different, the thing that does is also different