原生js的ajax的請求函式封裝
阿新 • • 發佈:2018-12-22
// 請求方式
// 請求地址
// 請求引數
// 返回值
<script> // 請求方式 // 請求地址 // 請求引數 // 返回值 function ajaxTools(pattern,url,parameter,func){ // 建立ajax let xhr = new XMLHttpRequest(); let gt = url; // 判斷請求方式 if(pattern.toLowerCase() == "get"){ gt += parameter; } // 傳參 xhr.open(pattern,gt,true); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 || xhr.status == 200){ // xhr.responseText回撥值 回撥函式 func(xhr.responseText); } } // 傳送請求 if(pattern.toLowerCase()=="post"){ xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send(parameter); }else{ xhr.send(); } } </script>
<!-- 封裝存在非同步操作
可使用promise解決問題 後續發出-->