axios、fetch 和 ajax的区别 在网络上存在很多文章。个人现针对自己的情况,来重新来整理一份。便于自己记忆和理解。内容参考了网络上的众多文章。
XMLHttpRequest
浏览器通过XMLHttpRequest 对象进行 http 通信。
传统Ajax 指的是 XMLHttpRequest(XHR),最早出现的向后端发送请求的技术,隶属于原始 js 中, 核心使用 XMLHttpRequest 对象,多个请求之间如果有先后关系的话,就会出现回调地狱
推荐一篇有关 XMLHttpRequest 的文章:XMLHttpRequest ——必知必会
常用语法:
一个简单的 http 请求
let xhr = new XMLHttpRequest(); xhr.open('GET', '/url', true); xhr.send();
一个稍微完整的 http 请求
let xhr = new XMLHttpRequest(); // 请求成功回调函数 xhr.onload = e => { console.log('request success'); }; // 请求结束 xhr.onloadend = e => { console.log('request loadend'); }; // 请求出错 xhr.onerror = e => { console.log('request error'); }; // 请求超时 xhr.ontimeout = e => { console.log('request timeout'); }; // 请求回调函数.XMLHttpRequest标准又分为Level 1和Level 2,这是Level 1和的回调处理方式 // xhr.onreadystatechange = () => { // if (xhr.readyState !== 4) { // return; // } // const status = xhr.status; // if ((status >= 200 && status < 300) || status === 304) { // console.log('request success'); // } else { // console.log('request error'); // } // }; xhr.timeout = 0; // 设置超时时间,0表示永不超时 // 初始化请求 xhr.open('GET/POST/DELETE/...', '/url', true || false); // 设置期望的返回数据类型 'json' 'text' 'document' ... xhr.responseType = ''; // 设置请求头 xhr.setRequestHeader('', ''); // 发送请求 xhr.send(null || new FormData || 'a=1&b=2' || 'json字符串');
这个是从网上找的。如果粗看官网提供的文档,可能需要很久的时间才能明白究竟怎么用。此处我先列出引用下。
JQuery ajax
菜鸟教程:AJAX 是一种与服务器交换数据的技术,可以在不重新载入整个页面的情况下更新网页的一部分。
基本语法:
$.ajax({ type: 'POST', // GET 或 POST url: url, // 发送请求的 URL data: data, // 要发送到服务器的数据 dataType: dataType, // 预期的服务器响应的数据类型 success: function () {}, // 请求成功时运行的函数 error: function () {} // 请求失败要运行的函数 });
缺点:
- 针对MVC的编程,不符合前端MVVM的浪潮
- 基于原生XHR开发,而XHR本身的架构不清晰 (我觉得此处应该是说官方给出的文档架构不清晰。)
- JQuery整个项目太大,单纯使用Ajax 却要引入整个JQuery,非常的不合理(采取个性化打包的方案又不能享受CDN服务)