网站首页 > 知识剖析 正文
JavaScript 初学者学完语法,进入实际的网页编程,一定有人告诉你,要掌握一个叫做 XMLHttpRequest 的东西。
脚本都靠它发出 HTTP 请求,跟服务器通信。所谓的 AJAX 操作就是基于它实现的。要是没有它,就不会有单页应用。
这个 XMLHttpRequest 对象,不仅名字怪,用法也非常独特。
let xhr = new XMLHttpRequest;
xhr.open('GET', url)
xhr.onload = function {
if (this.status === 200) {
let data = JSON.parse(this.responseText);
console.log(data);
}
};
xhr.onerror = function (err) {
console.log('Error Occurred :', err);
}
xhr.send;
就是因为写起来麻烦,实际开发中,往往使用它的各种封装库,比如早期的 jQuery。
$.get("test.php", function (data) {
$("body")
.append("Name: " + data.name)
.append("Time: " + data.time);
}, "json");
早期的封装库都使用回调函数,很不直观。后来的封装库都改用 Promise 的写法,比如 axios。
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
这样用起来,确实方便了,但是需要加载外部库,而它又是一个天天用到的基本需求。所以,浏览器厂商最终决定,抛弃 XMLHttpRequest,另起炉灶,重写一套全新的 API,内置在浏览器里面。
这就是 Fetch API,它使用fetch
发出请求,返回的是 Promise 对象。
fetch('https://api.github.com/users/ruanyf')
.then(response => response.json)
.then(json => console.log(json))
.catch(err => console.log('Request Failed', err));
Promise 可以使用 await 语法,表达起来跟同步操作一模一样。
async function getJSON {
let url = 'https://api.github.com/users/ruanyf';
try {
let response = await fetch(url);
return await response.json;
} catch (error) {
console.log('Request Failed', error);
}
}
Fetch API 的优点是写法简单,缺点是这个 API 包含的内容非常多,想要完全掌握并不容易。
我一直想写一篇教程,完整介绍它的各种用法,便于自己使用的时候查找。现在终于写出来,以后可以告别 XMLHttpRequest 了。
http://www.ruanyifeng.com/blog/2020/12/fetch-tutorial.html
(完)
- 上一篇: JavaScript篇面试题
- 下一篇: java ajax优缺点及实现的流程
猜你喜欢
- 2025-05-24 前端面试:异步加载和延迟加载的理解?
- 2025-05-24 dart系列之:浏览器中的舞者,用dart发送HTTP请求
- 2025-05-24 Ajax异步JavaScript和XML
- 2025-05-24 编写个人的Ajax:感受前端异步世界的魅力
- 2025-05-24 SpringBoot 项目处理跨域的四种技巧
- 2025-05-24 前端——CORS跨域请求的限制与解决
- 2025-05-24 面试官:说说你对options请求的理解
- 2025-05-24 在B站看猫片被老板发现?不如按下F12学学HTTP
- 2025-05-24 Web性能的计算方式与优化方案(二)
- 2025-05-24 Spring Security在前后端分离项目中的使用
- 05-24前端面试:异步加载和延迟加载的理解?
- 05-24dart系列之:浏览器中的舞者,用dart发送HTTP请求
- 05-24Ajax异步JavaScript和XML
- 05-24编写个人的Ajax:感受前端异步世界的魅力
- 05-24SpringBoot 项目处理跨域的四种技巧
- 05-24前端——CORS跨域请求的限制与解决
- 05-24面试官:说说你对options请求的理解
- 05-24在B站看猫片被老板发现?不如按下F12学学HTTP
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)