javascript - 第二个 AJAX 调用不起作用
问题描述
最后更新
我意识到为什么在创建 result2 变量时我会变得未定义,我将其设置为 undefined 而不是let result2 = '';
将其设置为字符串。一旦我进行了调整,未定义的就消失了。最终的 script.js 如下。
更新 4
它终于起作用了,它归结为以下不正确的行,document.querySelectorAll("weathers").innerHTML = result2;
我不得不返回并将天气更改为id而不是类,我不得不将上面的行更改为document.querySelector("#weathers").innerHTML += result2;
现在它可以工作了。我只需要自己弄清楚为什么我的代码中出现未定义的图像。
更新 3
我已经到了最后一部分,如果我控制台记录我的结果,我会得到我想要的结果,如下所示:
有了这一行,我的 html 中没有任何内容,我document.querySelectorAll("weathers").innerHTML = result2;
将尝试其他方法,看看是否可以使其正常工作。如果您注意到虽然我在图像中的代码中得到一个未定义的内容,是否有人知道这是否会影响我没有得到任何输出的原因?我也没有收到错误消息。
更新 2
我进行了调整以消除太多代码,更新代码将仅在下面列出的我的 script.js 文件中。我得到以下输出,它是一个对象数组:
当我运行代码时,我收到以下错误消息:
未捕获的类型错误:无法读取 XMLHttpRequest.xhr2.onload (script.js:57) xhr2.onload @ script.js:57 load (async) loadWeathers @ script.js:33 处未定义的属性“名称”
我将使用正确的语法来提取我需要的信息,因为它现在是一个对象数组,而不仅仅是一个对象。
更新 1
通过下面的建议,我终于可以解决一些问题。现在我可以看到,不是一次给我一个城市,而是将所有城市放在 api 请求 url 中,我收到以下错误消息:
script.js:77 GET http://api.openweathermap.org/data/2.5/weather?q=San_Francisco,Miami,New_Orleans,Chicago,New_York_City&APPID=XXXXXXXX 404(未找到)
背景:
我正在学习 API 并正在构建一个迷你天气网络应用程序。在我开始在 Jquery 中做同样的事情之前,我正在学习很长的 Vanilla Javascript。
目标:
我想同时做两件事:
- 当用户输入城市名称时,会弹出一张带有天气信息的卡片。
- 当用户访问该页面时,页面上已经存在大约五个主要城市,如下所示:
到目前为止我所拥有的:
到目前为止,我已经能够构建输入功能,因此当用户输入城市名称时,页面上会弹出一张卡片,如下所示:
我还有一些代码可以进入下一个主题,这是我的问题。
问题:
我添加了第二个 ajax 调用,其中包含将添加到 URL 的城市数组。我添加了第二个按钮(“获取天气”)用于测试目的,当我单击该按钮时,所有城市都会像第一张图片一样弹出。我做了一些研究,但我发现的一切都涉及 jquery 而不是 vanilla javascript Ajax。我无法弄清楚为什么什么都没有填充。我检查了控制台是否有错误,但没有收到任何错误。当我检查网络流量时,我没有收到任何呼叫请求。我什么也没得到,我不知道为什么。
这是我的html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<LINK REL=StyleSheet HREF="style.css" TYPE="text/css">
<title>Current Weather App</title>
</head>
<body>
<main role="main">
<section class="jumbotron text-center">
<div class="container">
<h1 class="jumbotron-heading">Today's Weather</h1>
<p class="lead text-muted">Curious about weather in your location? Just fill in below and submit.</p>
<p>
<div class="input-group mb-3">
<input type="text" class="form-control" id="city">
<div class="input-group-append">
<button class="btn btn-outline-secondary" id="buttonW" type="button">Get Weather</button>
<button class="btn btn-outline-secondary" id="buttonW2" type="button">Get Weathers</button>
</div>
</div>
</p>
</div>
</section>
<div id="weather"></div>
<div class="album py-5 bg-light">
<div class="container">
<div class="row" id="weathers"></div>
</div>
</div>
</main>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
</script>
<script src="script.js"></script>
</body>
</html>
这是我的最终script.js 文件:
// Create an event listener
document.getElementById("buttonW").addEventListener("click", loadWeather);
document.getElementById("buttonW2").addEventListener("click", loadWeathers);
///////////////THIS IS PART OF THE loadWeathers///////////////////////////////////////////////////////////////////////////////////////////
function getCity(locations) {
for (let i = 0; i < locations.length; i++) {
}
return locations;
}
function loadWeathers() {
let xhr2 = new XMLHttpRequest();
const cities = [
"5368361",
"4173495",
"4335045",
"4887398",
"5128638"
];
const base_path2 =
"http://api.openweathermap.org/data/2.5/group?id=" + getCity(cities) + "&APPID=XXXXXXXXXXXXXXXXXXXXXX";
xhr2.open("GET", base_path2, true);
xhr2.onload = function () {
if (this.status == 200) {
let cityWeathers2;
try {
cityWeathers2 = JSON.parse(this.responseText);
} catch (e) {
// JSON not valid, show error message
}
console.log(cityWeathers2)
// //add weather info
for (let i = 0; i < cities.length; i++) {
let result2 = '';
result2 +=
`<div class="col-md-4">
<div class="card mb-4 box-shadow">
<div class="card-body">
<h5 class="card-title">${cityWeathers2.list[i].name}</h5>
<p class="card-text">Here are some weather details for your City</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">Weather: ${cityWeathers2.list[i].weather[0].main} <img class="card-img-top weather-icon" src="${getIconURL(cityWeathers2.list[i].weather[0].icon)}" alt="Card image cap"></li>
<li class="list-group-item">Temperature: ${convertKtoF(cityWeathers2.list[i].main.temp) }° </li>
<li class="list-group-item">Wind Speed: ${convertMPStoMPH(cityWeathers2.list[i].wind.speed) } </li>
<li class="list-group-item">Geo Location: ${cityWeathers2.list[i].coord.lat} , ${cityWeathers2.list[i].coord.lon}</li>
</ul>
</div>`
// console.log(result2)
document.querySelector("#weathers").innerHTML += result2;
}
}
}
xhr2.send();
}
function loadWeather() {
// console.log(city);
let xhr = new XMLHttpRequest();
const city = document.getElementById("city").value;
const base_path =
"http://api.openweathermap.org/data/2.5/weather?q=" + city + "&APPID=XXXXXXXXXXXXXXXXXXXXXXX";
xhr.open("GET", base_path, true);
xhr.onload = function () {
// const city = document.getElementById("city").value;
if (this.status == 200) {
let cityWeathers;
try {
cityWeathers = JSON.parse(this.responseText);
} catch (e) {
// JSON not valid, show error message
}
const result =
`<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">${cityWeathers.name}</h5>
<p class="card-text">Here are some weather details for your City</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">Weather: ${cityWeathers.weather[0].main} <img class="card-img-top weather-icon" src="${getIconURL(cityWeathers.weather[0].icon)}" alt="Card image cap"></li>
<li class="list-group-item">Temperature: ${convertKtoF(cityWeathers.main.temp) }° </li>
<li class="list-group-item">Wind Speed: ${convertMPStoMPH(cityWeathers.wind.speed) } </li>
<li class="list-group-item">Geo Location: ${cityWeathers.coord.lat} , ${cityWeathers.coord.lon}</li>
</ul>
</div>`;
document.getElementById("weather").innerHTML = result;
}
}
xhr.send();
}
// Convert from Kelvins to Fahrenheit
function convertKtoF(kelvin) {
return Math.round((kelvin - 273.15) * 1.8);
}
// Convert from Meters Per Second to Miles Per Hour
function convertMPStoMPH(mps) {
return (Math.round(10 * mps * 2.2369362920544) / 10) + " mph";
}
// Weather icon
function getIconURL(icon) {
return "https://openweathermap.org/img/w/" + icon + ".png";
}
任何指导或建议将不胜感激!
解决方案
我不能说请求的准确性(根据评论),但问题出在你的函数xhr2.send();
体内。xhr2.onload
对于多个城市,您可能需要使用城市 ID,请参阅https://openweathermap.org/current#severalid。正如您尝试做的那样,文档似乎没有按名称提及多个城市。
推荐阅读
- dictionary - 如何对从 DashMap 中提取的项目进行模式匹配?
- jq - 解析嵌套 JSON 并使用 jq 创建新键
- javascript - 我需要在组件中显示一个列表,但发送的数据(以 JSON 格式)未正确解析
- python - “numbers = [range(1, 11)]”和“numbers = list(range(1, 11))”之间的区别
- docker - client_max_body_size 未生效
- laravel - 启用 CentOS 7(LAMPP 和 Laravel)服务器通过 SSL 发送电子邮件
- reactjs - 在按钮单击时呈现不同的 youtube 视频
- python - 在 Python 中更新 2D 数组值 - 更新整列错误?
- java - 不包括 NULL 和空字符串的 CreateQuery 必须同时在 Oracle 和 mySQL 中工作
- spring-boot - REST Spring 启动验证导致代码重复