使用 Fetch API 和 XMLHttpRequest 进行资源请求
1. Fetch API 概述
Fetch API 提供了一种简单且强大的方式来发起网络请求,并处理服务器响应。它允许我们在不重新加载或导航页面的情况下异步请求和处理服务器数据,这正是 Ajax(Asynchronous JavaScript and XML)的核心思想。Fetch API 的核心是 Request
对象,它可以通过 Request()
构造函数生成。
创建 Request 对象
const request = new Request('https://api.example.com/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
发送 Fetch 请求
使用 fetch()
方法可以发送请求并处理响应:
fetch(request)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));