zoukankan      html  css  js  c++  java
  • axios和ajax及fetch原理浅析

    axios和ajax及fetch原理浅析
    这三个其实都是用来请求数据的,那他们的区别在哪里呢?其实 axios 和 ajax
    都是对XMLHttpRequest这个对象的封装;而fetch则是window下的一个方法,是一个更底层的方法。

    ajax
    其实重点就是首先实例一个XMLHttpRequest对象,用其中的open方法建立连接;send方法传输数据(前端传到后台);然后再利用onreadystatechange 监听readyState的变化,当其为4时,代表请求完成;简单的代码实现如下:

    const Ajax={
    get: function(url, fn) {
    // XMLHttpRequest对象用于在后台与服务器交换数据
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onreadystatechange = function() {
    // readyState 为4说明请求已完成
    if (xhr.readyState == 4 && xhr.status == 200) {
    // 从服务器获得数据
    fn.call(this, xhr.responseText);
    }
    };
    xhr.send();
    },
    // datat应为'a=a1&b=b1'这种字符串格式,在jq里如果data为对象会自动将对象转成这种字符串格式
    post: function (url, data, fn) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    // 添加http头,发送信息至服务器时内容编码类型
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && (xhr.status == 200)) {
    fn.call(this, xhr.responseText);
    }
    };
    xhr.send(data);
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    axios
    axios其实就是在ajax的基础上加了promise,具体如下:

    const myAxios = {
    get: function(url) {
    return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
    resolve(xhr.responseText)
    }
    };
    xhr.send();
    })
    },

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    fetch
    fetch的使用这里就不多做赘述,有很多这方面的文档。fetch首先不想ajax一样需要引入jq;如果想自己实现ajax呢,步骤相对于fetch来说也是相当的繁琐;同时fetch也加入了promise,解决了回调地狱的问题;使用fetch虽然简单,但是也有一些问题需要注意:

    cookie传递
    必须在header参数里面加上credientials: ‘include’,才会如xhr一样将当前cookies带到请求中去
    fetch和xhr的不同
    fetch虽然底层,但是还是缺少一些常用xhr有的方法,比如能够取消请求(abort)方法
    fetch在服务器返回4xx、5xx时是不会抛出错误的,这里需要手动通过,通过response中的ok字段和status字段来判断
    ————————————————
    版权声明:本文为CSDN博主「qq_39096319」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/qq_39096319/article/details/82347033

  • 相关阅读:
    Shared Memory in Windows NT
    Layered Memory Management in Win32
    软件项目管理的75条建议
    Load pdbs when you need it
    Stray pointer 野指针
    About the Rebase and Bind operation in the production of software
    About "Serious Error: No RTTI Data"
    Realizing 4 GB of Address Space[MSDN]
    [bbk4397] 第1集 第一章 AMS介绍
    [bbk3204] 第67集 Chapter 17Monitoring and Detecting Lock Contention(00)
  • 原文地址:https://www.cnblogs.com/dillonmei/p/12578559.html
Copyright © 2011-2022 走看看