Ajax
主页 > 网络编程 > Ajax >

AJAX原理以及axios、fetch区别

2022-04-11 | 秩名 | 点击:

AJAX原理

XMLHttpRequest(XHR)对象用于与服务器交互。通过 XMLHttpRequest 可以在不刷新页面的情况下请求特定 URL,获取数据。这允许网页在不影响用户操作的情况下,更新页面的局部内容。XMLHttpRequest 可以用于获取任何类型的数据,而不仅仅是 XML。甚至支持 HTTP以外的协议(包括 file:// 和 FTP),尽管可能受到更多出于安全等原因的限制。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

/** 1. 创建Ajax对象 **/

var xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');// 兼容IE6及以下版本

/** 2. 配置 Ajax请求 **/

xhr.open('get', url, true)

/** 3. 发送请求 **/

xhr.send(null); // 严谨写法

/** 4. 监听请求,接受响应 **/

xhr.onreadystatechange = function(){

    if(xhr.readyState == 4){

        if(xhr.status == 200){

            success(xhr.responseText);

        } else {

            /** false **/

            fail && fail(xhr.status);

        }

    }

}

其他更多XMLHttpRequest相关api

ajax 有那些优缺点?

Promise封装Ajax

promise 封装实现:

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

29

30

31

32

33

34

35

36

37

// promise 封装实现:

function getJSON(url) {

  // 创建一个 promise 对象

  let promise = new Promise(function(resolve, reject) {

    let xhr = new XMLHttpRequest();

 

    // 新建一个 http 请求

    xhr.open("GET", url, true);

 

    // 设置状态的监听函数

    xhr.onreadystatechange = function() {

      if (this.readyState !== 4) return;

 

      // 当请求成功或失败时,改变 promise 的状态

      if (this.status === 200) {

        resolve(this.response);

      } else {

        reject(new Error(this.statusText));

      }

    };

 

    // 设置错误监听函数

    xhr.onerror = function() {

      reject(new Error(this.statusText));

    };

 

    // 设置响应的数据类型

    xhr.responseType = "json";

 

    // 设置请求头信息

    xhr.setRequestHeader("Accept", "application/json");

 

    // 发送 http 请求

    xhr.send(null);

  });

  return promise;

}

JQ Ajax、Axios、Fetch的核心区别

JQuery Ajax

Ajax前后端数据通信「同源、跨域」

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

// 用户登录 -> 登录成功 -> 获取用户信息

/* 回调地狱 */

$.ajax({

    url: 'http://127.0.0.1:8888/user/login',

    method: 'post',

    data: Qs.stringify({

        account: '18310612838',

        password: md5('1234567890')

    }),

    success(result) {

        if (result.code === 0) {

            // 登录成功

            $.ajax({

                url: 'http://127.0.0.1:8888/user/list',

                method: 'get',

                success(result) {

                    console.log(result);

                }

            });

        }

    }

});

优缺点:

Axios

Axios也是对ajax的封装,基于Promise管理请求,解决回调地狱问题

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

axios({

    method: 'post',

    url: '/user/login',

    data: {

        username: 'name',

        password: 'password'

    }

})

.then(function (response) {

    console.log(response);

})

.catch(function (error) {

    console.log(error);

});

// 或使用 async await

(async function () {

    let result1 = await axios.post('/user/login', {

        username: 'name',

        password: 'password'

    });

    let result2 = await axios.get('/user/list');

    console.log(result1, result2);

})();

优缺点:

Fetch

Fetch是ES6新增的通信方法,不是ajax,但是他本身实现数据通信,就是基于promise管理的

1

2

3

4

5

6

7

try {

  let response = await fetch(url, options);

  let data = response.json();

  console.log(data);

} catch(e) {

  console.log("Oops, error", e);

}

示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

(async function () {

    let result = await fetch('http://127.0.0.1:8888/user/login', {

        method: 'post',

        headers: {

            'Content-Type': 'application/x-www-form-urlencoded'

        },

        body: Qs.stringify({

            name: 'name',

            password: 'password'

        })

    })

    let data = result.json();

    console.log(data)

?

    let result2 = await fetch('http://127.0.0.1:8888/user/list').then(response => {

        return response.json();

    });

    console.log(result2);

})();

优缺点:

补充:为什么要用axios?

axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:

三选一绝必是axios了。其流程图如下:

原文链接:https://juejin.cn/post/7083481149875421198
相关文章
最新更新