Handwritten native Ajax requests

steps

There are several steps to sending a native Ajax request

  1. Instantiate the XMLHttpRequest object to get the XHR object
  2. Call the open method of the XHR object. The open method takes three parameters: the request method (get or POST), the request URL (the content of the GET request is concatenated above the URL), and whether the request is asynchronous (which we do 99% of the time).
  3. Call the send method of the XHR object, where the GET request does not need to be passed and the POST request does
  4. Listen for the XHR object onreadyStatechange callback if readyState is 4(which means the response has been parsed and can be called on the client side). It then determines whether the current request succeeded or failed based on the status on the XHR object. Status corresponds to the HTTP code

ES6 class version

const GET = "GET";
const POST = "POST";
const noop = () = > {};

class Ajax {
  constructor() {
    // IE6 does not support XMLHttpRequest below. You need to instantiate ActiveXObject, but it is basically ignored
    this.xhr = XMLHttpRequest
      ? new XMLHttpRequest()
      : new ActiveXObject("Microsoft.XMLHTTP");
  }

  Formatting data / * * * * {10} name: 'aa', age: = > name = aa&age = 10 * /
  formatData(data = {}) {
    const arr = [];
    for (let key in data) {
      arr.push(encodeURIComponent(key) + "=" + data[key]);
    }
    return arr.join("&");
  }

  /** * Sends requests, including GET requests and POST requests */
  request(options = {}) {
    const self = this;
    this.data = this.formatData(options.data);
    this.type = (options.type || GET).toUpperCase();
    this.url = options.url;
    if (!this.url) {
      throw new Error("ajax url is required.");
    }
    this.success = options.success || noop;
    this.error = options.error || noop;

    if (this.type === GET) {
      this.xhr.open(this.type, this.url + "?" + this.data, true);
      this.xhr.send();
    } else if (this.type === POST) {
      this.xhr.open(this.type, this.url, true);
      this.xhr.setRequestHeader(
        "Content-Type"."application/x-www-form-urlencoded"
      );
      this.xhr.send(this.data);
    }
    this.xhr.onreadystatechange = function () {
      if (self.xhr.readyState === 4) {
        // 200- Request successful
        // 204- Request successful, but no resource returned
        // 206- Request successful, partial return
        if ([200.204.206].indexOf(self.xhr.status) > -1) {
          const result = self.xhr.responseText;
          typeof self.success === "function" &&
            self.success.call(self.xhr, result);
        } else {
          const error = self.xhr.responseText;
          typeof self.error === "function"&& self.error.call(self.xhr, error); }}}; }}Copy the code

Function version

// URL :" URL path "type: request type Data: request parameter type dataType: returned string type
function ajax({url,type,data,dataType}){
return new Promise(function(resolve,reject){
	//1. Create asynchronous request objects
	var xhr = new XHMLHttpRequest();
	//2. Bind listener events
	xhr.onreadystatechange=function(){
	// When the asynchronous request status changes to 4 and the returned status code is 200, the response is received successfully
		if(xhr.readyState==4&&xhr.status==200) {Json string is automatically converted when the received string type is JSON string
		if(dataType! = =undefined&&dataType.toLowerCase()==="json") {var res=JSON.parse(xhr.responseText)
                }else{Otherwise, the content of the returned response text is directly retrieved
		var res=xhr.responseText
                }
	// Pass the data back with a Promise, which is equivalent to getting the request data and returning itresolve(res); }}// If the request is a GET request, concatenate the request parameters after the URL
	if(type.toLowerCase()==="get"&&data! = =undefined){
		url+="?"+data;
	}
	3. Open the connection
	xhr.open(type,url,true);
	// If the request is a POST request, modify the request header
	if(type.toLowerCase()==="post") {// Add: sets the request header
		xhr.setRequestHeader("Content-Type"."application/x-www-form-urlencoded");
                }
	//4. Send request
	if(type.toLowerCase()==="post"&&data! = =undefined){ xhr.send(data); }else{
            xhr.send(null);
         })
Copy the code