一年都没写过博客了,不是懒,是不知有啥好写的。。。现在本人从一个后台开发.net的转向前端开发了。。。
之前去面试的时候,给面试官问过,有没有属于自己的ajax类,当时很奇怪,因为我基本上ajax开发都是用jquery来完成,后来想了想,也是应该写一个。
先看调用方式:
1 ajax.request( " ajax.html " ,{v:Math.random(),num: 1 }, function (data){ 2 // do something 3 }, ' get ' );
方式好像jquery哦。。。还是觉得这样调用方便些。。。
1 var ajax = { 2 // Xmlhttprequest类 3 Xmlhttprequest : function () { 4 this .xhr = false ; 5 }, 6 // 外部调用接口 7 request : function (url,data,callback,type) { 8 // 每次都创建一个Xmlhttprequest的对象,使ajax调用互不影响 9 var xhr = new this .Xmlhttprequest(); 10 xhr.request(url,data,callback,type); 11 } 12 } 13 // 将{num:1,t:'a'}这种json数据格式转为num=1&t=a这种字符串形式 14 var json2str = function (data){ 15 var _data = []; 16 17 for ( var name in data) { 18 _data.push(name + " = " + data[name]); 19 } 20 return _data.join( ' & ' ); 21 } 22 // 扩展Xmlhttprequest类的方法 23 ajax.Xmlhttprequest.prototype = { 24 // 创建XMLHttpRequest 25 createXmlHttpRequest : function (){ 26 27 if (window.XMLHttpRequest) { 28 return new XMLHttpRequest(); 29 } 30 else { 31 var a = [ " Msxml2.XMLHTTP " , " Microsoft.XMLHTTP " , " Msxml2.XMLHTTP.5.0 " , " Msxml2.XMLHTTP.4.0 " , " Msxml2.XMLHTTP.3.0 " ]; 32 for ( var i = 0 ,l = a.length;i < l;i ++ ){ 33 try { 34 return new ActiveXObject(a[i]); 35 } catch (e){}; 36 } 37 } 38 }, 39 // 回调函数 40 fnCallback : function (callback){ 41 42 if ( this .xhr.readyState === 4 && this .xhr.status === 200 ) { 43 callback ? callback( this .xhr.responseText): void ( 0 ); 44 } 45 }, 46 // ajax请求 47 request : function (url, data, callback, type){ 48 49 var that = this ; 50 var ispost = type === ' post ' ? true : false ; 51 52 ! ispost && (url += (url.indexOf( ' ? ' ) + 1 ? ' & ' : ' ? ' ) + json2str(data)); 53 54 this .xhr = this .createXmlHttpRequest(); 55 56 this .xhr.open(type,url, true ); 57 ispost ? this .xhr.setRequestHeader( " Content-Type " , " application/x-www-form-urlencoded " ): '' ; 58 this .xhr.onreadystatechange = function (){that.fnCallback(callback);}; 59 this .xhr.send(ispost ? json2str(data): null ); 60 } 61 }
这个类,肯定有不足的了,欢迎拍砖吧!每个人都有自己的习惯用法,最重要是适合用就行了!