ajax的簡單封裝

來源:互聯網
上載者:User

//--------------------------------------------------------------------------------------

//封裝XMLHTTP的Request類的代碼
var $ajax = new Object();
function getAjax() {
    var ajax = false;
    try {
        ajax = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
        try {
            ajax = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (E) {
            ajax = false;
        }
    }
    if (!ajax && typeof XMLHttpRequest != 'undefined') {
        ajax = new XMLHttpRequest();
    }
    return ajax;
}
//封裝XMLHTTP向伺服器發送請求的操作
$ajax.send = function (url, method, callback, data) {
    var req = getAjax();  //得到一個XMLHTTP的執行個體
    //當XMLHTTP的請求狀態發生改變時調用
    req.onreadystatechange = function () {
        // 當請求已經載入
        if (req.readyState == 4) {
            // 當請求返回成功
            if (req.status == 200) {
                // 當定義了成功回呼函數時,執行成功回呼函數
                if (callback)
                    callback(req, data);
            }
            // 當請求返回錯誤
            else {
                alert("當載入資料時發生錯誤 :\n" + req.status + "/" + req.statusText);
            }
            try {
                delete req;
                req = null;
            } catch (e) { }
        }
    }
    //如果以POST方式回傳伺服器
    if (method == "POST") {
        req.open("POST", url, true);
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.send(data);
    }
    //以GET方式請求
    else {
        req.open("GET", url, true);
        req.send(null);
    }
}

//進一步封裝XMLHTTP以POST方式發送請求時的代碼
$ajax.sendPOST = function (url, data, callback) {
    $ajax.send(url, "POST", callback, data);
}
//進一步封裝XMLHTTP以GET方式發送請求時的代碼
$ajax.sendGET = function (url, callback, args) {
    return $ajax.send(url, "GET", callback, args);
}

//--------------------------------------------------------------------------------------

以上代碼很容易但是完成了ajax的基本需求用法也很簡單:

 $ajax.sendPOST("Handler.ashx", "action=reply&" + parameter,

  function (req, data) {
                    var rel=req.responseText;

  }

 );

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.