原生JS封裝ajax函數


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 //兼容IE 10 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

                ajax({
                    type:"get",
                    url:"http://localhost:8080/AJAX_test/txt/pbl.lol",
                    success:function(msg){
                        var list = JSON.parse(msg);
                    }
                })
相關文章
相關標籤/搜索