AJAX and JSONP with native JS

 

When front-end development needs to interact with the back-end data, for convenience and speed, the AJAX method encapsulated in JQuery will be selected, but sometimes, we only need the AJAX request method of JQuery, and other functions are rarely used, which is obviously is not necessary. In fact, it is not difficult to implement AJAX with native JavaScript. Below we will demonstrate how to use native JS to build simple AJAX, as well as the implementation of cross-domain request JSONP.

The root of AJAX is XMLHttprequest, and a complete AJAX request generally includes the following steps:

  • Instantiate the XMLHttpRequest object
  • connect to the server
  • send request
  • receive response data

Below we encapsulate a simple ajax() method using native JS:

1   const Ajax = (object) => {
 2          object = object || {};
 3          object.data = object.data || {};
 4          // Determine the request type as AJAX or JSONP 
5          let json = object.jsonp ? Jsonp(object) : ajax(object);
 6  
7          // Set the ajax method 
8          function ajax(object) {
 9             // 1. Set the request method: if not specified, the default is GET 
10             object.type = (object.type | | 'GET' ).toUpperCase();
 11             // 2. Set the format of data data 
12             object.data = formatObject(object.data);
13             // 3. Instantiate the XMLHttpRequest object   
14             var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP' );
 15             // 4. Listen to the event, as long as the readyState changes, the readystatechange event will be called 
16             xhr.onreadystatechange = function (){
 17                 // The readyState property indicates the current active stage of the request/response process, 4 is complete, all response data has been received 
18                 if (xhr.readyState == 4 ) {
 19                     let status = xhr. status;
 20                     // status : The status code of the HTTP response, the beginning of 2 indicates success 
21                     if (status >=200 && status < 300){
 22                         let response = '' ;
 23                         // Determine the content type of the received data 
24                         let type = xhr.getResponseHeader('Content-type' );  
 25                         if (type.indexOf('xml') !== -1 && xhr.responseXML) {  
 26                            response = xhr.responseXML; // Document object response   
27                           } else  if (type === 'application/json' ) {  
 28                            response = JSON.parse(xhr.responseText); // JSON response   
29                           } else{  
 30                            response = xhr.responseText; // string response   
31                          }; 
 32                          // success callback function 
33                          object.success && object.success(response);  
 34                     } else {
 35                          object.error && object.error(response);  
 36                     }
 37                 }
 38             }
 39  
40             
41             // 5. Connect and transfer data 
42             if (object.type == 'GET' ) {
 43                // Three parameters: request method, request address (in the get method, the transmission data is added after the address), whether the request is asynchronous (there are very few cases of synchronous request); 
44                 xhr.open(object.type, object.url + '?' + object.data, true );  
 45                 xhr.send( null );  
 46              } else {  
 47                 xhr.open(object.type, object.url, true );  
 48                 // Required, set the content when submitting Type   
49                 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8' ); 
 50                 // Transfer data 
51                 xhr.send(object.data); 
 52              }
53          }
 54  
55              // data formatting method 
56          function formateObject(data){
 57             if (data){
 58                 let arr = [];
 59                 for (let name in data){
 60                     // encodeURIComponent(): used to Encode a part of the URI 
61                     arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
 62                 }
 63  
64                 // In order to prevent caching, add a random number 
65                 arr.push ('randomV=' + randomNumber());
 66                 returnarr.join('&' );
 67             } else {
 68                 console.error('The request data cannot be formatted' )
 69             }
 70          }
 71  
72          // Method for generating random numbers 
73          function randomNumber(){
 74              return Math.floor (Math.random()*10000+404 );
 75          }
 76  
77      };


Similarly, we can also implement a JSONP method

// Set the Jsonp method 
        function Jsonp(object) {
           // Create a script tag and add it to the page 
          let callbackName = object.jsonp,
              head = document.getElementsByTagName('head')[0 ];
           // Set the callback parameter name passed to the background   
          object.data['callback'] = callbackName;  
          let data = formateObject(object.data),
              script = document.createElement('script');  
          head.appendChild(script);  
          // Create JSONP callback function 
          // Create jsonp callback function   
          window[callbackName] = function (json) {  
              head.removeChild(script);  
              clearTimeout(script.timer);  
              window[callbackName] = null;  
              object.success && object.success(json);  
          };  
          // Send the request 
          script.src = object.url + '?' + data;  
           // In order to know whether the request is successful, set the timeout processing   
          if (object.time) {  
           script.timer = setTimeout(function() {  
            window[callbackName] = null;  
            head.removeChild(script);  
            object.error && object.error({  
             message: 'Request timed out' 
            });  
           }, time);  
          }  

        }

Let's try these two methods.
Create a new index.html file, create a new test.json and jsonp.php

 

Use nginx to build a simple server, because Google does not allow local files to make ajax requests by default:

 

 

test.json

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325284808&siteId=291194637