JavaScript 中的 HTTP GET 请求
在 JavaScript 中,我们通常使用 XMLHttpRequest
API 通过其方法在 Web 服务器和浏览器之间传输数据。最近,该楼层已归 Fetch
API 所有,因为它易于实现并启用了 Promise。
此外,Fetch
约定支持 ES6 更新和修改。
在这里,我们将演示仅使用 XMLHttpRequest
API 对象和 Fetch
API 从服务器获取 HTTP GET 请求
到 Web 浏览器的实例。
使用 XMLHttpRequest
API 检索 GET
请求
使用 XMLHttpRequest
API,我们将初始化一个名为 xmlhr
的对象并启动此 API 可用的其他方法。
首先,我们将使用 open
方法从服务器设置 GET
以及 URL
。
此外,我们将在 open
方法中看到一个 false
参数,该参数用于同步请求的情况下 true in the case of asynchronous requests
。
代码片段:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test</title>
</head>
<body>
<button onclick="httpGet('https://jsonplaceholder.typicode.com/todos/1')">Get</button>
<p id="get"></p>
</body>
</html>
function httpGet(theUrl) {
var xmlhr = new XMLHttpRequest();
xmlhr.open('GET', theUrl, false);
xmlhr.send(null);
document.getElementById('get').innerHTML = xmlhr.responseText;
return xmlhr.responseText;
}
输出:
使用 fetch
API 检索 GET
请求
如果你正在寻找一种简单且性能更好的方法来从服务器中提取数据,那么 fetch
API 使该过程非常方便。
正如你将在示例中看到的,此 API 的命令更具可预测性,并且易于跟踪工作方法。最初,你将获取 URL
,然后检测数据类型。
稍后我们将提取数据并检查是否有任何错误可用。最后,如果没有错误,输出将在控制台面板中预览。让我们检查一下代码以获得正确的理解。
代码片段:
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((r) => r.json())
.then((data) => console.log(data))
.catch((e) => console.log('error'));
输出:
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。