封裝Ajax代碼實例

封裝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('&'); 
}

 

You May Also Like