Add Event Handling
function addevent (obj, type, fn) {
if (Obj.addeventlistener) {
Obj.addeventlistener (Type, FN, false);
} else if (obj.attachevent) {
Obj.attachevent (' on ' + type, function () {
Fn.call (obj);
});
}
}
Remove event Handling
function removeevent (obj, type, fn) {
if (Obj.removeeventlistener) {
Obj.removeeventlistener (Type, FN, false);
} else if (obj.detachevent) {
Obj.detachevent (' on ' + type, fn);
}
}
Encapsulating Ajax
function Createxhr () {
if (XMLHttpRequest) {
return new XMLHttpRequest ();
}else{
return new ActiveXObject (' microsoft.xmlhttp ');
}
}
///Name value pairs are converted to strings
function params (data) {
var arr = [];
for (var i in data) {
Arr.push (encodeuricomponent (i) + ' = ' + encodeURIComponent (Data[i]));
}
Return Arr.join (' & ');
}
Function Ajax (obj) {
var xhr = createxhr ();
Obj.method = Obj.method.toUpperCase ()
Obj.url = Obj.url + '? rand= ' + math.random ();
Obj.data = params (obj.data);
if (Obj.method = = = ' GET ') {
Obj.url + = obj.url.indexOf ('? ') = =-1? '? ' + obj.data: ' & ' + obj.data;
}
if (Obj.async = = = True) {
Xhr.onreadystatechange = function () {
if (xhr.readystate = = 4) {
Callback ();
}
};
}
Xhr.open (Obj.method,obj.url,obj.async);
if (Obj.method = = = "POST") {
Xhr.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded ');
Xhr.send (Obj.data);
}else{
Xhr.send (null);
if (Obj.async = = = False) {
callback ();
Function Callback () {
if (xhr.status = =) {
obj.success (xhr.responsetext);
}else{
Alert (' Get data Error! Error code: ' + xhr.status + ', error message: '. Xhr.statustext);
}
}
}
Calling Ajax
Addevent (document, ' click ', function () {
Ajax ({
Method: ' Get ',
URL: ' demo.php ',
Data: {
' Name ': ' Lee '
},
Success:function (text) {
var result = Json.parse (text);
},
Async:true
});
});
4, native JavaScript package Ajax ———— Quack No. second