//Ajax 方法封装 //设置数据格式 function setData(data){ if(!data){ return ''; } else{ var arr = []; for(k in data){ if(!data.hasOwnProperty(k)) continue; if(typeof data[k] == 'function') continue; var value = data[k].toString(); var key = encodeURIComponent(k); value = encodeURIComponent(value); arr.push(key + '=' + value); } return arr.join('&'); } } //get()方法封装 function get(url,obj,callback){ var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); } else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } url = url + '?'+ setData(obj); xhr.open('get',url,true); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ callback(xhr.responseText); } } } xhr.send(null); } //post()方法封装 function post(url,obj,callback){ var xhr = null; var postBody = setData(obj); if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); } else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } xhr.open('post',url,true); xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ callback(xhr.responseText); } } } xhr.send(postBody); }