GET
请求是 HTTP 协议中的一种请求方法,用于从服务器获取资源。在 JavaScript 中,你可以使用多种方式来发起 GET
请求,包括使用浏览器内置的 XMLHttpRequest
对象或更现代的 fetch
API。
GET
是 HTTP 协议定义的几种主要请求方法之一,用于请求从服务器获取指定资源。GET
请求通常用于获取资源。GET
请求是最基本的 HTTP 请求方法,易于理解和实现。GET
请求可以被浏览器缓存,提高性能。在 JavaScript 中,主要有两种方式发起 GET
请求:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
GET
请求可能会被浏览器缓存,导致获取的数据不是最新的。可以通过添加时间戳或随机数来避免缓存。try...catch
或检查 response.status
来处理错误。xhr.onerror = function() {
console.error('Network Error');
};
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
这样,你就能更全面地理解和运用 GET
请求了。