• React:axios——Fetch发送Ajax请求


    前置说明

    1) React本身只关注于界面, 并不包含发送ajax请求的代码

    2) 前端应用需要通过ajax请求与后台进行交互(json数据)

    3) react应用中需要集成第三方ajax(或自己封装)

    常用的ajax请求库

    1) jQuery: 比较重, 如果需要另外引入不建议使用 

    2) axios: 轻量级, 建议使用

    1. 封装XmlHttpRequest对象的ajax
    2. promise风格
    3. 可以用在浏览器端和node服务器端

    3) fetch: 原生函数, 但老版本浏览器不支持

    1. 不再使用XmlHttpRequest对象提交ajax请求
    2. 为了兼容低版本的浏览器, 可以引入兼容库fetch.js

    使用前需要引用aixos

    axios 文档

    https://github.com/axios/axios

    1) GET请求

    axios.get('/user?ID=12345')
      .then(function (response) {//数据就在response里的data中,这里面可以写为箭头函数的方式(response) => {}
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    
    axios.get('/user', {
        params: {
          ID: 12345
        }
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

     

    2) POST请求

    axios.post('/user', {
    
        firstName: 'Fred',
    
        lastName: 'Flintstone'
    
    })
    
    .then(function (response) {
    
      console.log(response);
    
    })
    
    .catch(function (error) {
    
      console.log(error);
    
    
    });

    Fetch文档

    1) https://github.github.io/fetch/

    2) https://segmentfault.com/a/1190000003810652

    1) GET请求

    fetch(url).then(function(response) {
      return response.json()
    }).then(function(data) {
      console.log(data)
    }).catch(function(e) {
      console.log(e)
    });

    2) POST请求

    fetch(url, {
      method: "POST",
      body: JSON.stringify(data),
    }).then(function(data) {
      console.log(data)
    }).catch(function(e) {
      console.log(e)
    })

     

  • 相关阅读:
    C#
    if
    .net 5.0
    C# 未提供必须形参对应的实参
    EasyRTC报错 “[ERR] mod_local_stream.c:880 Unknown source default”排查
    EasyRTC通过公网进入会议室失败问题排查及解决
    【CF1558B】Up the Strip
    【AT Keyence2019E】Connecting Cities
    【洛谷P7470】岛屿探险
    【洛谷P6628】丁香之路
  • 原文地址:https://www.cnblogs.com/GOOGnine/p/12390638.html
Copyright © 2020-2023  润新知