Objective
Compared to JS, jquery saves us the lengthy code to get elements, without considering some troublesome compatibility issues, more convenient animation implementations, and more convenient method calls that make jquery really more comfortable. But jquery is still the package of JS, we should not only use the comfort of the deep understanding of the principle, so as to better use it.
First of all, we encapsulate the function to be able to pass the infinite number of parameters, in the use of the functions we are about to encapsulate, we need to use the object to pass parameters, in the form of the following:
Data is passed as a parameter to our encapsulated function
var data = {
//Data
User: "Yonghu1", pass
: ' 12345 ',
age:18,//
callback function
Success:function (data) {
alert (data);
}
}
Function Encapsulation:
1. Encapsulates an auxiliary function to stitch the incoming objects into a URL string
function Todata (obj) {
if (obj = = null) {return
obj;
}
var arr = [];
for (var i in obj) {
var str = i+ "=" +obj[i];
Arr.push (str);
Return Arr.join ("&");
}
2. Encapsulation Ajax
function Ajax (obj) {//Specify the default value of the Commit method Obj.type = Obj.type | |
"Get"; Set whether asynchronous, default to True (asynchronous) Obj.async = Obj.async | |
True Set the default value for data Obj.data = Obj.data | |
Null if (window.
XMLHttpRequest) {//non ie var ajax = new XMLHttpRequest ();
}else{//ie var ajax = new ActiveXObject ("Microsoft.XMLHTTP");
}//Differentiate Get and post if (Obj.type = "post") {Ajax.open (Obj.type,obj.url,obj.async);
Ajax.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
var data = Todata (Obj.data);
Ajax.send (data); }else{//get test.php?xx=xx&aa=xx var url = obj.url+ "?"
+todata (Obj.data);
Ajax.open (Obj.type,url,obj.async);
Ajax.send (); } Ajax.onreadystatechange = function () {if (ajax.readystate = 4) {if (ajax.status>=200&&ajax.s tatus<300 | |
ajax.status==304) {if (obj.success) {obj.success (ajax.responsetext); }}else{if (obj.error) {Obj.error (ajax.statUS); }
}
}
}
}
Summarize
The above is the original JS-like jquery to achieve the full content of the Ajax package, I hope this article on the content of everyone's study or work can bring some help, if you have questions you can message exchange.