原生JS封裝ajax函數

來源:互聯網
上載者:User

標籤:ext   ror   lol   res   ade   ams   window   func   cti   


1
function ajax(params) { 2 params.data = params.data || ""; 3 params.type = params.type || "get"; 4 if(!params.url) { 5 throw new Error("未指定串連"); 6 } 7 params.async = params.async || true; 8 var xhr; 9 //相容IE10 if(window.VBArray) {11 xhr = new ActiveXObject("Msxml2.XMLHTTP");12 } else {13 xhr = new XMLHttpRequest();14 }15 xhr.open(params.type, params.url, params.sync);16 //處理回呼函數17 xhr.onreadystatechange = function() {18 console.log(xhr.status);19 if(xhr.status == 200) {20 if(xhr.readyState == 4) {21 params.success ? params.success(xhr.responseText) : "";22 }23 } else {24 throw new Error("請求失敗,狀態代碼:" + xhr.status);25 }26 }27 if(params.type == "get") {28 xhr.send();29 } else {30 xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");31 xhr.send(params.data);32 }33 }

調用:

                ajax({                    type:"get",                    url:"http://localhost:8080/AJAX_test/txt/pbl.lol",                    success:function(msg){                        var list = JSON.parse(msg);                    }                })

 

原生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.