ajax簡(jiǎn)易封裝

花了比較久的時(shí)間去理解,碼字。
記錄防老。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<style>
</style>
</head>
<body>
<button id="btn">點(diǎn)我測(cè)試</button>
<script>
function ajax(opts) {
  var xhr = new XMLHttpRequest();
  var dataArr = [];
  var param = '';
  for (key in opts.data) {
    param = param + key + "=" + opts.data[key] + '&';
  }
  param = param.substr(0,param.length-1)

  if (opts.type === 'get') {
    getType()
  } else if (opts.type === 'post') {
    postType()
  }
  function getType() {
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status === '200' || '304') {
        var results = JSON.parse(xhr.response)
        opts.success(results)
      } else {
        opts.error()
      }
    }
    isDataloaded = true
  }
  isDataloaded = false
  xhr.open(opts.type, opts.url +"?"+param, true);
  xhr.send();
}

function postType() {
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status === '200' || '304') {
        var results = JSON.parse(xhr.response)
        opts.success(results)
      } else {
        opts.error()
      }
    }
    isDataloaded = true
  }
  isDataloaded = false
  xhr.open(opts.type, opts.url, true);
  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
  xhr.send(param);
}
}


var isDataloaded = true
document.querySelector('#btn').addEventListener('click', function(){
    ajax({
        url: '/login',   //接口地址
        type: 'get',               // 類型, post 或者 get,
        data: {
            username: 'xiaoming',
            password: 'abcd1234'
        },
        success: function(ret){
            console.log(ret);       // {status: 0}
        },
        error: function(){
           console.log('出錯(cuò)了')
        }
    })
})
</script>
</body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容