Encapsulate a simple ajax plugin yourself

This plug-in is mainly written by me to learn native ajax and function encapsulation, and there are still many bugs. Students who are also learning ajax and function encapsulation can refer to the reference, take the essence and discard the dross

 

function myAjax(obj) {
     var xmlHttp; //Save the xmlHttpRequest object
     var type = obj.requestType; //Save the request method
     var cache = obj.cache || false; //whether to use the cache when get, the default is no
     var success = obj.success; //Callback method for successful data request
     var error = obj.error; //Callback method for error
     var async = obj.async || false; //Asynchronous or not, default no
     var data = []; //Store the data sent by the user
     var url = obj.url; //User request address


     createXmlHttp(); //Execute the xmlHttp creation function

     // Failed to create xmlHttp
     if(!xmlHttp) {
        console.log("My brother, failed to create xmlHttp object! Your browser does not support xmlHttpRequest object");
     }

     try {
         //Define the state listener function
         xmlHttp.onreadystatechange = function () {
             switch (xmlHttp.readyState) {
                 case 1:
                     console.log("The open() method has been called, but the send() method has not been called. The request has not been sent.");
                     break;
                 case 2:
                     console.log("Send() method called, HTTP request sent to web server. No response received.");
                     break;
                 case 3:
                     console.log("All response headers have been received. Response body has been received but not completed.");
                     break;
                 case 4:
                     if (xmlHttp.status == 200) {
                         console.log("HTTP response has been fully received.");
                         success(xmlHttp.responseText); //Call the callback function
                     }
                     break;
                 default:
                     error(xmlHttp.statusText);
                     break;
             }
         };

         // Convert the data sent by the user to a string
         for (var i in obj.data) {
             data.push(i + '=' + obj.data[i]);
         }
         data = data.join('&');

         if (type.toUpperCase() == 'GET') { //If it is a get request
             if (cache == false) { //If the get request does not use the cache
                 xmlHttp.open('get', url + '?' + data + '&random=' + Math.random(), async);
                 xmlHttp.send('null');
             } else { //If the get request uses the cache
                 xmlHttp.open('get', url + '?' + data, async);
                 xmlHttp.send('null');
             }
         } else if (type.toUpperCase() == 'POST') //if it is a post request
         {
             xmlHttp.open('post', url, async);
             xmlHttp.setRequestHeader("Content-Type"
                 , "application/x-www-form-urlencoded");
             xmlHttp.send(data);
         } else {
            throw new Error('Your request method is wrong!');
         }
     } catch (error) {
         console.log("Error: " + error.message);
     }


    //Create xmlHttpRequest object function
    function createXmlHttp() {
        if(window.ActiveXObject) {
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }

        } else if (window.XMLHttpRequest){
            try {
                xmlHttp = new XMLHttpRequest();
            } catch(e) {
                xmlHttp = false;
            }
        }
    }

 }

 

The basic logic of the plugin:
    GET request:
    1. Create a new XHR object
    2. Define the state monitoring function, each state corresponds to various processing
    3. Call the open method to start the request, ready to send
    4. Use the send method to send the request, the parameter is null
  
    POST request:
    1. Create a new XHR object
    2. Define the state monitoring function, each state corresponds to various processing
    3. Use the open method to start the request, ready to send
    4. Set the Content-Type type of the http header information to simulate form sending
    5. Use the send method to send a request, the parameters are what you want to send
How to use the plugin:
  1. You can use it after introducing the myAjax.js file in the html page
  2.
    Example of get method usage: 
   myAjax({
      requestType: 'get',
      url: '/getFunc',
      async: true,
      cache: false,
      data: { name: "lin", age: "20"},
      success: function (data) {
          alert(data);
      },
      error: function (statusText) {
         alert("The request failed, the following is the specific information:\n" + statusText);
      }
     });

    Example of using the post method:
    myAjax({
     requestType: 'post',
     url: '/ postFunc',
     async: true,
     data: {name:"shuai", age: 10},
     success: function (data) {
         console.log(data);
     },
     error: function (statusText) {
         alert("The request failed, the following is the specific information:\n" + statusText);
     }
    });

 

 

 

 

 

.

Guess you like

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