封装ajax-2

来源:互联网 发布:linux arp命令 编辑:程序博客网 时间:2024/05/01 07:14
function uri(obj){var arr=[];for(var i in obj){arr.push(encodeURIComponent(i)+'='+encodeURIComponent(obj[i]));}return arr.join('&');}function createajax(obj){if(window.XMLHttpRequest){var xhr=new XMLHttpRequest();}else{var xhr=new ActiveXObject('Microsoft.XMLHTTP');}obj.data=uri(obj.data);if(obj.method=='GET'){obj.url+='?m='+Math.random()+'&'+obj.data;}else{obj.url+='?m='+Math.random();}xhr.open(obj.method,obj.url,obj.async);if(obj.method=='GET'){xhr.send(null);}else{xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");xhr.send(obj.data); }if(obj.async==false){if(xhr.status==200){obj.success(xhr.responseText);}else{alert(xhr.status);}}else{xhr.onreadystatechange=function(){if(xhr.readyState==4){if(xhr.status==200){obj.success(xhr.responseText);}else{alert(xhr.status);}}}}}