使用原生JS封装ajax方法
当项目只需要使用ajax而不需要引用jquery时,此时封装一个ajax方法非常必要,下面给出主要代码
function ajax(obj){ obj.method = obj.method.toUpperCase()||'POST'; obj.url = obj.url||''; obj.async= obj.async||true; obj.data = obj.data||null; obj.success = obj.success ||function(){}; //新建xml对象 var xml= null; if(window.XMLHttpRequest){ xml= new XMLHttpRequest(); }else{ //兼容IE xml= new ActiveXObject("Microsoft.XMLHTTP"); } var arr = []; for(attr in obj.data){ arr.push(attr+'='+obj.data[attr]); } var postData = arr.join('&'); if(obj.method.toUpperCase()==='POST'){ //当请求方式为‘POST’时 xml.open(obj.method,obj.url,obj.async); xml.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8'); xml.send(postData); }else if(obj.method.toUpperCase()=='GET'){ //当请求方式为‘GET’时 xml.open(obj.method,obj.url,obj.async); xml.send(null); } //设置回调函数 xml.onreadystatechange=function(){ if(xml.readyState==4&&xml.status==200){ obj.success(xml.responseText); } } }
函数使用实例:
ajax({ method:'POST', url:'test.php', data:{ name1:'value1', name2:'value2' } success:function(response){ dosomethingwith(response); } })