封装Ajax代码实例
程序员文章站
2022-06-04 11:43:51
封装ajax代码实例
//封装ajax
function ajax(obj) {
var xhr = new createxhr();
obj...
封装ajax代码实例
//封装ajax function ajax(obj) { var xhr = new createxhr(); obj.url = obj.url + '?rand=' + math.random(); obj.data = params(obj.data); if (obj.method === 'get') obj.url = obj.url.indexof('?') == -1 ? obj.url + '?' + obj.data : obj.url + '&' + obj.data; if (obj.async === true) { xhr.onreadystatechange = function () { if(xhr.readystate==4)callback(); }; } xhr.open(obj.method,obj.url,obj.async); if(obj.method==='post'){ xhr.setrequestheader('content-type','application/x-www-form-urlencoded'); xhr.send(obj.data); }else{ xhr.send(null); } if(obj.async===false){ callback(); } function callback(){ if(xhr.status==200){ obj.success(xhr.responsetext); //回调 }else{ alert('数据返回失败!状态代码: '+xhr.status+',状态信息: '+xhr.statustext); } } } //调用ajax addevent(document,'click',function(){ //ie6需要重写addevent ajax({ method:'get', url:'demo.php', data:{ 'name':'lee', 'age':100 }, success:function(text){ alert(text); }, async:true }); }); //名值对编码 function params(data){ var arr=[]; for(var i in data){ arr.push(encodeuricomponent(i)+'='+encodeuricomponent(data[i])); } return arr.join('&'); }