【发布时间】:2021-10-11 15:39:57
【问题描述】:
有一段 javascript 代码(来自令人惊叹的 CodingTrain 系列!!):
我的问题如下:
我们在第 28 行将数据对象传递给 fetch-Post 请求。在第 17 行首先声明了两个变量 latand lon,但未初始化。然后在第 20 行使用它们构建数据对象最终在第 28 行传递给 fetch 函数。
我不明白这两个变量如何保存代码中已经存在的地理位置值。因为我们仅在下面的第 35-40 行中获得了地理位置。可能这与 async 和 await 逻辑的工作方式有关,但我不确定。
01: <!DOCTYPE html>
02: <html lang="en">
03: <head>
04: <meta charset="UTF-8" />
05: <meta name="viewport" content="width=device-width, initial-scale=1.0" />
06: <meta http-equiv="X-UA-Compatible" content="ie=edge" />
07: <title>Document</title>
08: </head>
09: <body>
10: <h1>Data Selfie App</h1>
11: <p>
12: latitude: <span id="latitude"></span>°<br />
13: longitude: <span id="longitude"></span>°
14: </p>
15: <button id="submit">submit</button>
16: <script>
17: let lat, lon;
18: const button = document.getElementById('submit');
19: button.addEventListener('click', async event => {
20: const data = { lat, lon };
21: const options = {
22: method: 'POST',
23: headers: {
24: 'Content-Type': 'application/json'
25: },
26: body: JSON.stringify(data)
27: };
28: const response = await fetch('/api', options);
29: const json = await response.json();
30: console.log(json);
31: });
32:
33: if ('geolocation' in navigator) {
34: console.log('geolocation available');
35: navigator.geolocation.getCurrentPosition(async position => {
36: lat = position.coords.latitude;
37: lon = position.coords.longitude;
38: document.getElementById('latitude').textContent = lat;
39: document.getElementById('longitude').textContent = lon;
40: });
41: } else {
42: console.log('geolocation not available');
43: }
44: </script>
45: </body>
46: </html>
github repo 的链接是这样的:https://github.com/CodingTrain/Intro-to-Data-APIs-JS
【问题讨论】:
-
在您单击按钮之前,第 20 行不会运行。我们假设 API 会在用户点击之前返回数据并分配变量。
标签: javascript html node.js async-await fetch