文件名:SydAjax.js
1 /** 2 * @desc javascript Ajax 3 * @parameter opt 4 * @parameter string opt.type post/get, 5 * @parameter string opt.url 6 * @parameter string opt.data or json object 7 * @parameter function opt.success 8 * @parameter function opt.error 9 * @author Sydney 10 * @date 2013年6月3日 11 */ 12 var SydAjax = { 13 ajax:function(opt){ 14 var xhr = this.createXhrObject(); 15 xhr.onreadystatechange = function(){ 16 if(xhr.readyState!=4) return ; 17 (xhr.status===200 ? 18 opt.success(xhr.responseText,xhr.responseXML): 19 opt.error(xhr.responseText,xhr.status)); 20 } 21 xhr.open(opt.type,opt.url,true); 22 if(opt.type!=='post') 23 opt.data=null; 24 else 25 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 26 opt.data = this.parseQuery(opt.data); 27 xhr.send(opt.data); 28 }, 29 post:function(url,success,data){ 30 var popt = { 31 url:url, 32 type:'post', 33 data:data, 34 success:success, 35 error:function(data){} 36 } 37 this.ajax(popt); 38 }, 39 get:function(url,success){ 40 var gopt = { 41 url:url, 42 type:'get', 43 success:success, 44 error:function(){} 45 } 46 this.ajax(gopt); 47 }, 48 createXhrObject:function(){ 49 var methods = [ 50 function(){ return new XMLHttpRequest();}, 51 function(){ return new ActiveXObject('Msxml2.XMLHTTP');}, 52 function(){ return new ActiveXObject('Microsoft.XMLHTTP');} 53 ]; 54 for(var i=0;len=methods.length,i<len;i++){ 55 try{ 56 methods[i](); 57 }catch(e){ 58 continue; 59 } 60 this.createXhrObject = methods[i]; 61 return methods[i](); 62 } 63 throw new Error('Could not create an XHR object.'); 64 }, 65 parseQuery:function(json){ 66 if(typeof json == 'object'){ 67 var str = ''; 68 for(var i in json){ 69 str += "&"+i+"="+encodeURIComponent(json[i]); 70 } 71 return str.length==0 ? str : str.substring(1); 72 }else{ 73 return json; 74 } 75 } 76 };