ajax简易封装

2017-03-19  本文已影响0人  饥人谷_風逝

花了比较久的时间去理解,码字。
记录防老。

<!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">点我测试</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('出错了')
        }
    })
})
</script>
</body>
</html>
上一篇下一篇

猜你喜欢

热点阅读