Python语言技术文档

微信小程序技术文档

php语言技术文档

jsp语言技术文档

asp语言技术文档

C#/.NET语言技术文档

html5/css技术文档

javascript

点击排行

您现在的位置:首页 > 技术文档 > ajax

也写一个Ajax.Request类附代码

来源:中文源码网    浏览:274 次    日期:2024-04-28 06:07:11
【下载文档:  也写一个Ajax.Request类附代码.txt 】


也写一个Ajax.Request类附代码
目的:因为blog程序里的某些模块需要用到ajax,直接使用prototype.js体积比较大(40多k),而且仅仅用到其中的ajax功能,因此为了减轻下载的负担,又不能改动已经在prototype.js框架下写好的代码,只能是按照prototype的风格,自己写一个ajax类,达到零成本移植框架。 新的ajax类如下: var Ajax = {xmlhttp:function(){ try{ return new ActiveXObject('Msxml2.XMLHTTP'); }catch(e){ try{ return new ActiveXObject('Microsoft.XMLHTTP'); }catch(e){ return new XMLHttpRequest(); } } } }; Ajax.Request = function(){ if (arguments.length<2) return; var _p = {asynchronous:true,method:"GET",parameters:""}; //default option for (var key in arguments[1]){ // custom option overwrite default option _p[key] = arguments[1][key]; } var _x = Ajax.xmlhttp(); //xml obj var _url = arguments[0]; //str if(_p["parameters"].length>0) _p["parameters"] += '&_='; if(_p["method"].toUpperCase()=="GET")_url += (_url.match(/\?/) ? '&' : '?') + _p["parameters"]; _x.open(_p["method"],_url,_p["asynchronous"]); _x.onreadystatechange = function(){ if (_x.readyState==4){ if(_x.status==200){ _p["onComplete"]?_p["onComplete"](_x):""; }else{ _p["onError"]?_p["onError"](_x):""; } } } if(_p["method"].toUpperCase()=="POST")_x.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); _x.send(_p["method"].toUpperCase()=="POST" ? _p["parameters"] : null); }; 这个类保存成js文件,体积还不到1k,足够小了。哈哈。 调用方法: var myAjax = new Ajax.Request( "http://localhost/abc.asp", { method:"post", parameters:"demo=123456789abc", onComplete:function(xmlhttp){ alert(xmlhttp.responseText) } } ); 调用的风格完全与原来相同! 目前这个新类只有两个回调函数:onComplete 与 onError,Ajax类也只有Request一个方法,毕竟现在blog程序还不需要这么多应用嘛。parameters 属性有个默认值:{asynchronous:true,method:"GET",parameters:""},可以从中知道,如果调用时不传入asynchronous、method、parameters三个参数,那么类将使用默认值。

相关内容