js學習總結----ajax相容處理及惰性思想

來源:互聯網
上載者:User

標籤:length   new   需要   沒有   erro   blog   soft   重寫   技巧   

封裝代碼如下:

// var xhr = null;// //為了相容IE6及更低的版本:如果第一個不支援,則瀏覽器會報錯,後面就不在執行了// try{//     xhr = new ActiveXObject("Microsoft.XMLHTTP");// }catch(e){// }// if(new ActiveXObject("Microsoft.XMLHTTP")){//     xhr = new ActiveXObject("Microsoft.XMLHTTP");// }else if(new ActiveXObject("Msxm12.XMLHTTP")){//     xhr = new ActiveXObject("Msxm12.XMLHTTP");// }else if(new ActiveXObject("Msxm13.XMLHTTP")){//     xhr = new ActiveXObject("Msxm13.XMLHTTP");// }//JS高階編程技巧之"惰性思想":能夠執行一次就搞定的不會執行多次//createXHR:建立AJAX對象,相容所有的瀏覽器function createXHR(){    var xhr = null,        flag = false,        ary = [            function(){                return new XMLHttpRequest;            },            function(){                return new ActiveXObject("Microsoft.XMLHTTP");            },            function(){                return new ActiveXObject("Msxm12.XMLHTTP")            },            function(){                return new ActiveXObject("Msxm13.XMLHTTP");            }        ];    for(var i = 0,len = ary.length;i<len;i++){        var curFn = ary[i];        try{            xhr = curFn();            //本次迴圈擷取的方法執行沒有出現錯誤:說明此方法是我想要的,我們下一次直接執行這個小方法即可,這就需要我們把createXHR重寫為小方法即可(完成後不需要判斷下面的,直接退出迴圈即可)            createXHR = curFn;            flag = true;            break;        }catch(e){            //本次迴圈擷取的方法執行出現錯誤:繼續執行下一次的迴圈        }            }    if(!flag){        throw new Error("your brower is not support ajax,please change your brower,try again!")    }    return xhr;}

 

js學習總結----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.