第一次開我的技術博客了,發的第一篇技術文章,歡迎指點……html
歡迎訪問本人的獨立博客:藍克比爾ajax
Ajax的實現主要分爲四部分:緩存
一、建立Ajax對象服務器
// 建立ajax對象 var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); } else { //爲了兼容IE6 xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
二、鏈接服務器app
// 鏈接服務器open(方法GET/POST,請求地址, 異步傳輸) xhr.open('GET', 'data.txt', true);
三、發送請求dom
// 發送請求 xhr.send();
四、接收返回數據異步
// 處理返回數據 /* ** 每當readyState改變時,就會觸發onreadystatechange事件 ** readyState屬性存儲有XMLHttpRequest的狀態信息 ** 0 :請求未初始化 ** 1 :服務器鏈接已創建 ** 2 :請求已接受 ** 3 : 請求處理中 ** 4 :請求已完成,且相應就緒 */ xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ /* ** Http狀態碼 ** 1xx :信息展現 ** 2xx :成功 ** 3xx :重定向 ** 4xx : 客戶端錯誤 ** 5xx :服務器端錯誤 */ if(xhr.status == 200){ success(xhr.responseText); } else { if(failed){ failed(xhr.status); } } } }
Ajax封裝函數:函數
function Ajax(type, url, data, success, failed){ // 建立ajax對象 var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject('Microsoft.XMLHTTP') } var type = type.toUpperCase(); // 用於清除緩存 var random = Math.random(); if(typeof data == 'object'){ var str = ''; for(var key in data){ str += key+'='+data[key]+'&'; } data = str.replace(/&$/, ''); } if(type == 'GET'){ if(data){ xhr.open('GET', url + '?' + data, true); } else { xhr.open('GET', url + '?t=' + random, true); } xhr.send(); } else if(type == 'POST'){ xhr.open('POST', url, true); // 若是須要像 html 表單那樣 POST 數據,請使用 setRequestHeader() 來添加 http 頭。 xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send(data); } // 處理返回數據 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ success(xhr.responseText); } else { if(failed){ failed(xhr.status); } } } } } // 測試調用 var sendData = {name:'asher',sex:'male'}; Ajax('get', 'data/data.html', sendData, function(data){ console.log(data); }, function(error){ console.log(error); });
歡迎訪問本人的獨立博客:藍克比爾測試