问题描述
我是在 JavaScript 中使用 API 的新手。我希望获得用户放入站点(城市名称)上的框中的输入并获取 API,以检索该城市的温度。到目前为止,我有以下内容来获取 API。但是我对如何实际获取该数据并显示它有点迷茫。我将如何获得“数据”?我只是不习惯在 Javascript 中使用 API 并希望了解更多信息。
js 文件:
public static IntNode addBefore(IntNode front,int target,int newItem) {
while(front.next != null) {
if(front.next.data == target) {
IntNode neww = new IntNode(newItem,front.next);
front.next = neww;
return neww;
}
front = front.next;
}
return null;
}
然后我有这个。 searchUser 只是代表用户输入的位置:
function hi() {
function temperature(input) {
const myKey = "Hidden_for_privacy";
const api = `https://api.openweathermap.org/data/2.5/weather?
q=${input}&lang=en&&appid=${myKey}&units=metric`;
fetch(api)
.then(function(response){
let data = response.json();
console.log(data);
return data;
})
相关 HTML:
const search = document.getElementById("searchUser");
const button = document.getElementById("submit");
button.addEventListener("click",() => {
const currentVal = search.value;
解决方法
我认为在您可以在屏幕上显示数据之前,您遇到了一些语法错误。我建议首先专注于 JS 实现,以确保您成功获取数据并将其加载到控制台。例如,JS 中的闭包可能会导致问题。 hi
函数正在创建一个闭包,然后您将输入的参数传递到其中的函数中,但没有可获取的局部变量。
也许尝试这样的事情来启动并查看它记录的内容:
function getTemperature() {
const myKey = "Hidden_for_privacy";
const api = `https://api.openweathermap.org/data/2.5/weather?
q=${input}&lang=en&&appid=${myKey}&units=metric`;
// .json returns a promise so you need to use .then to get the data from it synchronously
fetch(api)
.then((response) => response.json())
.then(data => console.log(data))
}