关于javascript:原生-ajax-封装

27次阅读

共计 3288 个字符,预计需要花费 9 分钟才能阅读完成。

一、AJAX 简介

  • AJAX 全称为 Asynchronous Javascript And XML,就是异步的 JS 和 XML。
  • 通过 AJAX 能够在浏览器中向服务器发送异步申请,最大的劣势:无刷新获取数据。
  • AJAX 不是新的编程语言,不是新的一门独立的技术,而是一种应用现有规范的新办法。

二、AJAX 的工作原理

  • Ajax 的工作原理相当于在用户和服务器之间加了一个中间层 (Ajax 引擎),使用户操作与服务器响应异步化。

三、AJAX 的特点

  • AJAX 的长处

    1. 能够无需刷新页面而与服务器端进行通信。
    2. 容许你依据用户事件来更新局部页面内容。
  • 毛病

    1. 没有浏览历史,不能回退
    2. 存在跨域问题
    3. SEO 不敌对

四、根本应用

// 1. 创立 XMLHttpRequest 对象
let xhr
if (window.XMLHttpRequest) {xhr = new XMLHttpRequest()
} else if (window.ActiveObject) {
  // 兼容 IE6 以下版本
  xhr = new ActiveXobject('Microsoft.XMLHTTP')
}

// 2. 设置申请信息
xhr.open('get', 'http://localhost:3000/test_get')

// 3. 发送申请
xhr.send() // get 申请不传 body 参数,只有 post 申请应用
/*
      4. 接管响应
        - xhr.responseXML 接管 xml 格局的响应数据
        - xhr.responseText 接管文本格式的响应数据
*/
xhr.onreadystatechange = function () {
  /*
          xhr.readyState 能够用来查看申请以后的状态
            0: 对应常量 UNSENT,示意 XMLHttpRequest 实例曾经生成,然而 open() 办法还没有被调用。1: 对应常量 OPENED,示意 send() 办法还没有被调用,依然能够应用 setRequestHeader(),设定 HTTP 申请的头信息。2: 对应常量 HEADERS_RECEIVED,示意 send() 办法曾经执行,并且头信息和状态码曾经收到。3: 对应常量 LOADING,示意正在接管服务器传来的 body 局部的数据,如果 responseType 属性是 text 或者空字符串,responseText 就会蕴含曾经收到的局部信息。4: 对应常量 DONE,示意服务器数据曾经齐全接管,或者本次接管曾经失败了
        */
  if (xhr.readyState == 4) {
    let status = xhr.status
    if ((status >= 200 && status < 300) || status == 304) {options.success && options.success(xhr.responseText, xhr.responseXML)
    } else {options.error && options.error(status)
    }
  }
}

五、解决 IE 缓存问题

  • 问题:在一些浏览器中 (IE), 因为缓存机制的存在,ajax 只会发送的第一次申请,残余屡次申请不会在发送给浏览器而是间接加载缓存中的数据。
  • 解决形式:浏览器的缓存是依据 url 地址来记录的,所以咱们只须要批改 url 地址即可防止缓存问题
xhr.open('get', 'http://localhost:3000/test_get' + Date.now())

六、AJAX 封装

// 格式化申请参数
function formatParams(data) {let arr = []
  for (let name in data) {arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]))
  }
  arr.push(('v=' + Math.random()).replace('.', ''))
  return arr.join('&')
}
function ajax(options) {options = options || {} // 调用函数时如果 options 没有指定,就给它赋值 {}, 一个空的 Object
  options.method = (options.method || 'GET').toUpperCase() // 申请格局 GET、POST,默认为 GET
  options.dataType = options.dataType || 'json' // 响应数据格式,默认 json
  options.timeout = options.timeout || 30000
  let params = formatParams(options.data) // options.data 申请的数据
  let xhr
  // 思考兼容性
  if (window.XMLHttpRequest) {xhr = new XMLHttpRequest()
  } else if (window.ActiveObject) {
    // 兼容 IE6 以下版本
    xhr = new ActiveXobject('Microsoft.XMLHTTP')
  }

  // 启动并发送一个申请
  if (options.method == 'GET') {xhr.open('get', options.url + '?' + params, true)
    xhr.send(null)
  } else if (options.method == 'POST') {xhr.open('post', options.url, true)
    // 设置表单提交时的内容类型
    // Content-type 数据申请的格局
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    xhr.send(params)
  }

  // 设置无效工夫
  setTimeout(function () {if (xhr.readySate != 4) {xhr.abort()
    }
  }, options.timeout)
  /*
    接管
    options.success 胜利之后的回调函数  options.error 失败后的回调函数
    xhr.responseText,xhr.responseXML  取得字符串模式的响应数据或者 XML 模式的响应数据
  */
  xhr.onreadystatechange = function () {if (xhr.readyState == 4) {
      let status = xhr.status
      if ((status >= 200 && status < 300) || status == 304) {options.success && options.success(xhr.responseText, xhr.responseXML)
      } else {options.error && options.error(status)
      }
    }
  }
}
// 根本的应用实例
ajax({
  url: 'http://localhost:3000/test_get',
  method: 'get',
  data: {
    name: 'name',
    age: 24,
  },
  success: function (data) {console.log(data, 'asdasdsa')
  },
})

七、get/post

  • 能够应用后面封装的 ajax 函数
function get(url, data, callback) {
  ajax({
    url,
    method: 'get',
    data,
    success(result) {callback(result)
    },
  })
}
function post(url, data, callback) {
  ajax({
    url,
    data,
    method: 'post',
    success(result) {callback(result)
    },
  })
}

// 测试 get
get('http://localhost:3000/test_get', { name: 'name', age: 24}, function (data) {console.log(data, 'get')
})
// 测试 post
post('http://localhost:3000/test_post', { name: 'name', age: 24}, function (data) {console.log(data, 'post')
})

正文完
 0