Encapsulate your own Ajax function

1. The effect to be achieved

myAjax({
      method: 'Request type',
      url: 'Request address',
      data: {
       // 'Request parameter object'
      },
      success: function (res) {  // Successful callback function
        console.log(res)  // Print data
      }
})

2. Define options parameter options

The myAjax() function is our custom Ajax function, it receives a configuration object as a parameter, and the following properties can be configured in the configuration object.

  • method request type
  • url The requested URL address
  • data The data carried by the request
  • success The callback function after the request is successful

3. Processing data parameters

The data object needs to be converted into the format of the query string and submitted to the server, so the resolveData function is defined in advance as follows.

/**
 *
 * @param {*} data Turn the object into a query string
 * username=tom&age=20
 */
// Turn the object into a query string
function resolveData(data) {
  var arr = [];
  for (var key in data) {
    var str = key + '=' + data[key]; //key=value
    arr.push(str);
  }
  return arr.join('&'); //Convert array to string and separated by &
}

4. Define the myAjax function

In the myAjax() function, you need to create an xhr object, determine the type of request, and judge the request type if… else…

function myAjax(options) {
  // Create xhr object
  let xhr = new XMLHttpRequest();
  var params = resolveData(options.data);
  // Determine whether the request method is GET or post
  //toUpperCase() Method is used to convert a string to uppercase
  if (options.type.toUpperCase() == 'GET') {
    //2.transfer open    options.url + '?' + params
    xhr.open(options.type, params ? options.url + '?' + params : options.url);
    xhr.send();
  } else if (options.type.toUpperCase() == 'POST') {
    xhr.open(options.type, options.url);
    // Set request header
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    // Set data
    xhr.send(params);
  }
}

5. Listen for registration events

Listen to the onreadystatechange event

 // Register to listen
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      // Convert the server's json string into a js object
      var obj = JSON.parse(xhr.responseText);
      options.success && options.success(obj);
    }
  };

Leave a Reply