First, we need the xhr object. This is not difficult for us, encapsulating it into a function.
var createAjax = function() { var xhr = null; try { //IE series browser 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) { // Initialize // Type parameter, optional var type = conf.type; // Url parameter, required var url = conf.url; // Data parameter is optional, only var data = conf.data; // Datatype parameter is optional var dataType = conf.dataType; // Callback function is optional var success = conf.success; if (type == null){ // Type parameter is optional, default is get type = "get"; } if (dataType == null){ // DataType parameter is optional, 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){ //Normal 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){ //Convert json string to js object success(eval("("+xhr.responseText+")")); } } } } } };};Finally, let’s explain the usage of this function.
ajax({ type:"post", url:"test.jsp", data:"name=dipoo&info=good", dataType:"json", success:function(data){ alert(data.name); } });The above example code that uses native JS to simply encapsulate AJAX is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.