js 代碼
- function ajax(method,synchronous){
- this._httpReq = false; /*ajax初始化對象*/
- this.method = method; /*get|post*/
- this.syn = synchronous; /*是否採用異步請求,默認true*/
- this.url = ""; /*提交異步請求的url地址*/
- this.resType = ""; /*異步請求返回數據類型text|xml*/
- this.callback = ""; /*異步請求完成後的回滾函數*/
- this.loading = ""; /*load函數*/
- this.content = null; /*Ajax中send方法的參數*/
- this.readystate = -1; /*ajax的請求狀態*/
- this.state = -1; /*http請求響應代碼*/
- /************ get/set方法開始 ***************/
- //設置提交異步請求的url地址
- this.setUrl = function (url){
- this.url = url;
- }
- //設置異步請求返回數據類型text|xml
- this.setResType = function (restype){
- this.resType = restype;
- }
- //設置回滾函數
- this.setCallback = function (func){
- this.callback = func;
- }
- //設置load函數
- this.setLoading = function (loadFunc){
- this.loading = loadFunc;
- }
- //設置send自帶的參數值,默認null
- this.setContent = function (contents){
- this.content = contents;
- }
- /*********get/set方法結束*******/
- /*********狀態顯示方法*********/
- //調用window.alert方法
- this.alert = function (msg){
- window.alert(msg);
- }
- //調用window.status的方法
- this.status = function (msg){
- window.status = msg;
- }
- /*********狀態顯示方法結束*********/
- /*************執行方法開始*****************/
- //創建HttpXMLRequest
- this.createXMLRequest = function(){
- if(window.XMLHttpRequest){
- this._httpReq = new XMLHttpRequest();
- if(this._httpReq.overrideMimeType){
- this._httpReq.overrideMimeType("text/xml");
- }
- }else if(window.ActiveXObject){
- try{
- this._httpReq = new ActiveXObject("Msxml2.XMLHTTP");
- }catch(e){
- try{
- this._httpReq = new ActiveXObject("Microsoft.XMLHTTP");
- }catch(e){}
- }
- }
- }
- //初始化ajax對象
- this.init = function(){
- this.createXMLRequest();
- }
- //發送一個http請求
- this.send = function (){
- if(this.resType.toLowerCase()=="post"){
- _httpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
- }
- this._httpReq.open(this.method,this.url,this.syn);
- this._httpReq.send(this.content);
- }
- //取消一個http請求
- this.abort = function (){
- this._httpReq.abort();
- }
- this.callbackState = function(){
- switch(this._httpReq.readyState){
- case 0:
- this.readystate = 0;
- break;
- case 1:
- this.readystate = 1;
- break;
- case 2:
- this.readystate = 2;
- break;
- case 3:
- this.readystate = 3;
- break;
- case 4:
- this.readystate = 4;
- switch(this._httpReq.status){
- case 200:
- eval(this.callback);
- break;
- case 202:
- this.status("請求處理中,還沒處理完畢!");
- break;
- case 400:
- this.status("錯誤的請求!");
- break;
- case 404:
- this.status("請求資源未找到!");
- break;
- case 500:
- this.status("內部服務器錯誤,請聯繫管理員!");
- break;
- default:
- this.status("返回數據失敗,"+this._httpReq.status);
- break;
- }
- break;
- default:
- this.readystate = 0;
- break;
- }
- }
- this.onReadyStateChange = function (){
- var owner = this;
- this._httpReq.onreadystatechange = function(){
- owner.callbackState.call(owner);
- }
- }
- /*************執行方法結束*****************/
- }
雖然跟網上有些ajax封裝類有些類似,但這個確實是我自己寫出來的,雖然寫得不是特別好,而且還有些功能還沒完善,不過這個js類的確可以用來在小項目使用一些ajax技術時非常方便。歡迎批評!!