寫在前面的話,若是中間有什麼不明白的,請先看封裝ajax框架!(前言篇)php
(function(){})();html
在一個項目中,可能會引用多個js框架,若是函數名相同,會有命名衝突,因此這裏使用封閉函數。ajax

但$是局部變量,外面不能直接使用,因此須要添加window.$ = $;json
表示爲全局對象window添加一個"$"的屬性,這個屬性的值是當前局部變量$的值。瀏覽器
因此在外部,若是想獲取某個dom元素,能夠直接:$("content");緩存
由於以前,咱們將一個函數賦值給了$,函數也是對象,因此$也就是一個對象服務器
爲對象$添加一個get方法,參數有三個app
url:表示ajax請求的頁面地址框架
data:表示get請求時所須要傳遞的參數dom
callback:當ajax獲得正確的數據後,所執行的回調函數,也就是參數callback接收的參數應該是一個函數。

爲對象$添加一個post方法,參數有三個
url:表示ajax請求的頁面地址
data:表示get請求時所須要傳遞的參數
callback:當ajax獲得正確的數據後,所執行的回調函數,也就是參數callback接收的參數應該是一個函數。
當調用ajax請求時,可使用這種形式
$.method(頁面地址,傳遞參數,處理函數);
那麼對應的方法中callback參數就指向了這個處理函數,因此callback(xhr.responseText);至關於處理函數(xhr.responseText)
咱們在ajax程序中,可使用三種數據形式:
a、字符串
b、xml
c、json
須要完善ajax框架 ,能夠返回不一樣類型的數據,再進行不一樣的處理。首先,爲get和post方法添加第四個參數:type,表示指望獲得的返回值類型
再根據type值的不一樣,返回對應的數據
調用形式
$.method(請求地址,參數,處理函數,數據類型);
1 (function(){ 2 //用於獲得一個dom對象 3 var $ = function(id){ 4 return document.getElementById(id); 5 }; 6 //用於獲得一個ajax對象 7 $.init = function(){ 8 try{return new ActiveXObject();}catch(e){} 9 try{ 10 return new XMLHttpRequest(); 11 }catch(e){ 12 alert("請更換瀏覽器!"); 13 } 14 }; 15 //用於發送ajax的get請求調用方法爲$.get("demo.php","username=zhangsan&&age=20",function(result){},'json') 16 $.get = function(url,data,callback,type){ 17 var xhr = $.init(); 18 //首先判斷下傳遞的data參數是否爲null,若是不爲空直接拼接到url後傳遞給服務器 19 if(data !=null){ 20 url = url+"?"+data; 21 } 22 xhr.open("get",url); 23 //解決緩存問題 24 xhr.setRequestHeader("If-Modified-since","0"); 25 xhr.onreadystatechange = function(){ 26 if(xhr.readyState == 4 && xhr.status == 200){ 27 //若是沒有傳遞type參數,讓其默認爲text 28 if(type == null){ 29 type ='text'; 30 } 31 if(type == 'text'){ 32 callback(xhr.responseText); 33 } 34 if(type == 'xml'){ 35 callback(xhr.responseXML); 36 } 37 if(type == 'json'){ 38 callback(eval("("+xhr.responseText+")")); 39 } 40 } 41 }; 42 xhr.send(null); 43 }; 44 //用於發送ajax的post請求,調用方法爲$.post("demo.php","username=zhangsan&&age=20",function(result){},'json') 45 $.post = function(url,data,callback,type){ 46 var xhr = $.init(); 47 xhr.open("post",url); 48 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 49 xhr.onreadystatechange = function(){ 50 if(xhr.readyState == 4 && xhr.status == 200){ 51 //若是沒有傳遞type參數,讓其默認爲text 52 if(type == null){ 53 type ='text'; 54 } 55 if(type == 'text'){ 56 callback(xhr.responseText); 57 } 58 if(type == 'xml'){ 59 callback(xhr.responseXML); 60 } 61 if(type == 'json'){ 62 callback(eval("("+xhr.responseText+")")); 63 } 64 } 65 }; 66 xhr.send(data); 67 }; 68 window.$ = $; 69 })();