ajax的封裝

來源:互聯網
上載者:User

標籤:ajax 自調用匿名函數

    利用自調用匿名函數對ajax進行封裝,會節省我們很多精力重複地書寫代碼。下面封裝了get、post兩種請求,以及text、xml、json資料類型傳輸。如下:    (function(){    //1、用於得到一個DOM元素    //定義了一個$函數 範圍有局部    var $ = function(id){        return document.getElementById(id);    };        //2、用於得到一個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.$ = $;})();

本文出自 “做一隻蝸牛真好” 部落格,請務必保留此出處http://smili.blog.51cto.com/8919945/1565331

ajax的封裝

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.