用原生JS對AJAX做簡單封裝

m5de 9年前發布 | 3K 次閱讀 JavaScript

首先,我們需要xhr對象。這對我們來說不難,封裝成一個函數。

var createAjax = function() { var xhr = null; try { //IE系列瀏覽器 xhr = new ActiveXObject("microsoft.xmlhttp");
    } catch (e1) { try { //非IE瀏覽器 xhr = new XMLHttpRequest();
        } catch (e2) { window.alert("您的瀏覽器不支持ajax,請更換!");
        }
    } return xhr;
}; 

然后,我們來寫核心函數。

var ajax = function(conf) { // 初始化 //type參數,可選 var type = conf.type; //url參數,必填  var url = conf.url; //data參數可選,只有在post請求時需要 var data = conf.data; //datatype參數可選  var dataType = conf.dataType; //回調函數可選 var success = conf.success; if (type == null){ //type參數可選,默認為get type = "get";
    } if (dataType == null){ //dataType參數可選,默認為text dataType = "text";
    } // 創建ajax引擎對象 var xhr = createAjax(); // 打開 xhr.open(type, url, true); // 發送 if (type == "GET" || type == "get") {
        xhr.send(null);
    } else if (type == "POST" || type == "post") {
        xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        xhr.send(data);
    }
    xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { if(dataType == "text"||dataType=="TEXT") { if (success != null){ //普通文本 success(xhr.responseText);
                }
            }else if(dataType=="xml"||dataType=="XML") { if (success != null){ //接收xml文檔  success(xhr.responseXML);
                }  
            }else if(dataType=="json"||dataType=="JSON") { if (success != null){ //將json字符串轉換為js對象  success(eval("("+xhr.responseText+")"));
                }
            }
        }
    };
}; 

最后,說明一下此函數的用法。

 ajax({ type:"post",
        url:"test.jsp",
        data:"name=dipoo&info=good",
        dataType:"json",
        success:function(data){ alert(data.name); } }); 

 本文由用戶 m5de 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!