javascript封装的ajax函数库
下面是封装好的ajax的函数
1 function AjaxObj() { 2 this.xmlHttp = null; 3 this.Request = function(method, url, data, callback, sync) { 4 if (window.ActiveXObject) { 5 this.xmlHttp = new ActiveXObject("Microsoft.XMLHttp"); 6 } else if (window.XMLHttpRequest) { 7 this.xmlHttp = new XMLHttpRequest(); 8 if (this.xmlHttp.overrideMimeType) { 9 this.xmlHttp.overrideMimeType('text/xml'); 10 } 11 } 12 if (this.xmlHttp) { 13 var self = this; 14 if (callback) 15 this.xmlHttp.onreadystatechange = function(){callback(self.xmlHttp);}; 16 else 17 this.xmlHttp.onreadystatechange = function(){return;}; 18 if (!method) 19 method = "POST"; 20 method = method.toUpperCase(); 21 if (method == 'GET') { 22 this.xmlHttp.open('GET', url + ((typeof data=="string")?('?' + data):""), typeof sync == "boolean" ? sync : true); 23 this.xmlHttp.send(null); 24 } else { 25 this.xmlHttp.open('POST', url, typeof sync == "boolean" ? sync : true); 26 this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); 27 this.xmlHttp.send(data); 28 } 29 } 30 }; 31 this.abort = function() { 32 if (this.xmlHttp) 33 this.xmlHttp.abort(); 34 }; 35 this.swRequest = function(cfg){ 36 if(!cfg.url) 37 return; 38 this.Request(cfg.method||"POST",cfg.url||"",cfg.data,function(req){ 39 if(req.readyState==4){ 40 if(req.status==200||req.status==0){ 41 var obj = null; 42 var text = req.responseText; 43 eval("obj = "+ text); 44 cfg.success.call(cfg.soap||this,obj); 45 return; 46 }else{ 47 cfg.failure.call(cfg.soap||this,"错误!"); 48 return; 49 } 50 } 51 }); 52 }; 53 }
调用方法:
1 ajax.swRequest({ 2 method:"POST", 3 sync:false, 4 url:'?a=manage&m=checkUser', 5 data:"user="+user.value, 6 success: function(msg) { 7 if(msg==1){ 8 flag.value = 'true'; 9 } else { 10 flag.value = ''; 11 } 12 }, 13 failure: function(a) { 14 alert(a); 15 }, 16 soap:this 17 });
本文链接:javascript封装的ajax函数库
联系作者:javascript博客
版权所有:非特殊说明都是本站原创文章,转载请注明出处

浙公网安备 33010602011771号