Example code of simple encapsulation of AJAX with native JS

  • 2021-07-04 17:40:47
  • OfStack

First, we need the xhr object. This is not difficult for us to encapsulate into a function.


var createAjax = function() { var xhr = null; try { //IE Series browsers  xhr = new ActiveXObject("microsoft.xmlhttp");
  } catch (e1) { try { // Non IE Browser  xhr = new XMLHttpRequest();
    } catch (e2) { window.alert(" Your browser does not support ajax , please replace! ");
    }
  } return xhr;
}; 

Then, let's write the core function.


var ajax = function(conf) { //  Initialization  //type Parameter , Optional  var type = conf.type; //url Parameter, required  var url = conf.url; //data Parameter is optional, only in the post Required when requested  var data = conf.data; //datatype Optional parameters  var dataType = conf.dataType; // Callback function optional  var success = conf.success; if (type == null){ //type Parameter is optional, and the default is get type = "get";
  } if (dataType == null){ //dataType Parameter is optional, and the default is text dataType = "text";
  } //  Create ajax Engine object  var xhr = createAjax(); //  Open  xhr.open(type, url, true); //  Send  if (type == "GET" || type == "get") {
    xhr.send(null);
  } else if (type == "POST" || type == "post") {
    xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    xhr.send(data);
  }
  xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { if(dataType == "text"||dataType=="TEXT") { if (success != null){ // Ordinary text  success(xhr.responseText);
        }
      }else if(dataType=="xml"||dataType=="XML") { if (success != null){ // Receive xml Document  success(xhr.responseXML);
        } 
      }else if(dataType=="json"||dataType=="JSON") { if (success != null){ // Will json String is converted to js Object  success(eval("("+xhr.responseText+")"));
        }
      }
    }
  };
}; 

Finally, explain the usage of this function under 1.


 ajax({ type:"post",
    url:"test.jsp",
    data:"name=dipoo&info=good",
    dataType:"json",
    success:function(data){ alert(data.name); } }); 


Related articles: