利用自調用匿名函數對ajax進行封裝,會節省咱們不少精力重複地書寫代碼。下面封裝了get、post兩種請求,以及text、xml、json數據類型傳輸。以下: (function(){ //一、用於獲得一個DOM元素 //定義了一個$函數 做用域有局部 var $ = function(id){ return document.getElementById(id); }; //二、用於獲得一個Ajax對象 //將$看做函數對象,init爲屬性,值爲函數體 $.init = function(){ try{return new XMLHttpRequest()}catch(e){} try{return new ActiveXObject('Microsoft.XMLHTTP')}catch(e){} alert('請更改新瀏覽器!'); }; //用於發送Ajax get請求 $.get = function(url,data,callback,type){ var xhr = $.init(); if (data != null){//傳遞參數、只發出請求 url = url+'?'+data; } xhr.open('get',url); xhr.setRequestHeader('If-Modified-Since','0');//解決get緩存問題 xhr.onreadystatechange = function(){ if (xhr.readyState == 4 && xhr.status == 200){ //當沒有指定傳值類型時,默認爲字符串 if (type == null){ type = 'text'; } //判斷語句指定三種接收形式 if (type == 'text'){ callback(xhr.responseText); } if (type == 'xml'){ callback(xhr.responseXML); } if (type == 'json'){ callback(eval("("+xhr.responseText+")")); } } }; xhr.send(null); }; //用於發送Ajax post請求 $.post = function(url,data,callback,type){ var xhr = $.init(); xhr.open('post',url); xhr.setRequestHeader('content-type','application/x-www-form-urlencoded'); xhr.onreadystatechange = function(){ if (xhr.readyState == 4 && xhr.status == 200){ //當沒有指定傳值類型時,默認爲字符串 if (type == null){ type = 'text'; } //判斷語句指定三種接收形式 if (type == 'text'){ callback(xhr.responseText); } if (type == 'xml'){ callback(xhr.responseXML); } if (type == 'json'){ callback(eval("("+xhr.responseText+")")); } } }; xhr.send(data); }; //增大其做用域全局變量 window方法的$屬性 賦值爲$ 閉包寫法 window.$ = $; })();