美文网首页
ajax简易封装

ajax简易封装

作者: 饥人谷_風逝 | 来源:发表于2017-03-19 20:36 被阅读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>
    

    相关文章

      网友评论

          本文标题:ajax简易封装

          本文链接:https://www.haomeiwen.com/subject/hvsvnttx.html