网络请求

现代的前端项目都是前后端分离开发模式进行的,也就避免不了前端需要给后端服务器发送网络请求,对数据进行增删改查的操作。

发起网络请求的方法我们可以总结为4种:

  • xhr - 原生的ajax

    • 缺点:代码繁多

    • 语法:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      const xhr = new XMLHttpRequest()
      xhr.open(请求方式, 请求路径, 是否异步)
      xhr.send()
      xhr.onreadystatechange = function() {
      if(xhr.readyState === 4) {
      if(xhr.status >= 200 && xhr.status < 300) {
      let res = xhr.responseText
      }
      }
      }

      xhr.onload = function() {
      let res = xhr.responseText
      }

      其他请求方式的原理,就是原生ajax

  • jquery的ajax请求 - jquery库封装好的ajax请求

    • 语法

      • 下载

      • 引入

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        $.get(路径, 成功回调函数, 希望返回的数据格式)
        $.post(路径, 成功回调函数, 希望返回的数据格式)
        $.ajax({
        url: '',
        method: '',
        data: '',
        dataType: '',
        async: true,
        success: res => {},
        error: res => {}
        })
    • 优点:功能强大,内置promise

    • 缺点:jquery大部分代码是封装的dom,有牛刀宰鸡的感觉

  • fetch - H5自带的请求

    • 语法:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      fetch(路径, {
      method: '',
      body: '携带的数据'
      }) // 返回promise对象
      .then(resp => {
      // resp是一个响应对象 - 可以通过resp决定后续希望得到的数据格式
      return resp.text()
      return resp.json()
      })
      .then(res => {
      // res是最终得到的结果数据
      })
    • 优点:不用下载,内置,写法简单

    • 缺点:需要then两次

  • axios - 现在比较流行的ajax封装

    • 语法:

      • 下载

      • 引入

        1
        2
        3
        4
        5
        6
        7
        8
        axios.get(路径).then(res => {})
        axios.post(路径, 请求主体).then(res => {})
        axios({
        method: '',
        url: '',
        headers: {},
        data: ''
        }).then(res => {})
      • 全局配置

        1
        2
        axios.defaults.baseURL = 'http://localhost:8888'// 设置基准地址
        axios.defaults.headers['Authorization'] = 'token令牌'// 设置请求头信息,通用头信息
    • 优点:写法简单,功能强大

    • 缺点:第三方的,需要下载

我们在企业项目中,通常使用fetch和axios来发送请求。