JavaScript封装回调函数(委托)

JavaScript封装回调函数(委托)

封装

    function ajax (method, url, params, done) {
      method = method.toUpperCase()
      var xhr = new XMLHttpRequest()

      if (typeof params === 'object') {
        var tempArr = []
        for (var key in params) {
          var value = params[key]
          tempArr.push(key + '=' + value)
        }
        params = tempArr.join('&')
      }

      if (method === 'GET') {
        url += '?' + params
      }

      xhr.open(method, url,)

      var data = null
      if (method === 'POST') {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        data = params
      }

      xhr.onreadystatechange = function () {
        if (this.readyState !== 4) return
        // 不应该在封装的函数中主观的处理响应结果
        done(this.responseText)
      }

      xhr.send(data)
    }

调用

  var onDone = function (res) {
      console.log('hahahahaha')
      console.log('hohohohoho')
      console.log(res)
      console.log('做完了')
    }

    ajax('get', 'time.php', {}, onDone)

你可能感兴趣的:(JavaScript)