脚本都靠它发出 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
(完)