jquery - 我的 API 调用未显示我正在调用的数据
问题描述
我正在尝试让我的天气预报网站显示天气。这是我的代码。我觉得我已经正确地写了这个,但是输出却另有说明。我已经写了这是Jquery。
我感觉 AJAX 调用的 IF 语句有问题。
非常感谢
PS。我故意取出天气应用程序的钥匙。
谢谢。
// Wait until Dom has completed loading
$(document).ready(function() {
// Testing that logic.js has been successfully linked to index.html.
console.log("logic.js is linked successfully");
// GLOBAL VARIABLES
// SELECTORS
// selectors for left side column
let searchCity = $(".searchCity");
let cityList = $(".cityList");
let searchButton = $(".searchButton");
let searchHistory = [];
// selectors for right side column
let weatherArea = $(".weatherArea");
let forecastArea = $(".cardArea");
// VARIABLES for AJAX
let searchedCity = $(searchCity).val();
let queryURL = "api.openweathermap.org/data/2.5/forecast?q=" + searchedCity + "&appid=APIKEYGOESHERE"
// I took out my key for this question
// BUILDING FUNCTIONS
// When user clicks search button...
$(searchButton).click(function(event) {
event.preventDefault();
console.log("requesting weather data...");
// Push user's search into variable array
searchHistory.push(searchedCity);
// If the search field is not blank... -- This if statement may be breaking my code, still testing
if (searchedCity != "") {
// Locally store searchHistory -- having issues getting this to work
localStorage.setItem("searchHistory", searchHistory);
// Request weather data from OpenWeatherMap API
$.ajax({
url: queryURL,
method: "GET",
dataType: "jsonp",
})
// When weather data response is returned...
.then(function(response) {
console.log(response);
// Display weather data in weatherArea
let weatherData = show(response);
$(weatherArea).html(weatherData);
// Display forecast data in forecastArea
let forecastData = "";
// For each item in response...
for (var i in response.list) {
if (i > 0 && response.list[i].dt_txt.indexof("12:00") > -1) {
// Create variable to contain forecast data
let forecastArray = [
"<div class = 'col-sm-2 day'>",
"<p>",
response.list[i].dt_txt.split(" ")[0],
"</p>",
"<img src = 'http://openweathermap.org/img/wn/' + response.list[i].weather[0].icon + '@2x.png'>",
"<p> Temp: ",
response.list[i].main.temp,
" degrees</p>",
"<p> Humidity: ",
response.list[i].main.humidity,
"%</p>",
"<p> Wind Speed: ",
response.list[i].main.wind.speed,
" mph</p>",
"</div>"
];
// Add forecast Data to forecastArray
forecastData += forecastArray.join("");
}
}
// Display forecast data in forecastArea
$(forecastArea).html(forecastData);
$(searchCity).val("");
});
}
// If the search field is empty...
else {
$(weatherArea).text("Search field can't be empty");
$(forecastArea).text("Search field can't be empty");
}
});
// function for showing the response data for the weather
function show(response) {
console.log("Showing Response: ", response);
return response.city.name + "<h3> (" + response.list[0].dt_txt.split(' ')[0] + ") </h3>" +
"<p class = 'lead'>Temp: " + response.list[0].main.temp + " degrees</p>" +
"<p class = 'lead'>Humidity: " + response.list[0].main.humidity + " %</p>" +
"<p class = 'lead'>Wind Speed: " + response.list[0].wind.speed + " mph</p>";
};
// Get searh history from local storage and display in cityList
function showHistory() {
let searchStorage = localStorage.getItem("searchHistory")
$(cityList).append("<tr>").append("<td>" + searchStorage + "</td>")
};
showHistory();
// Close of 'document.ready' function
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<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="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet">
<link rel="stylesheet" href="./assets/style.css">
<title>Weather Dashboard</title>
</head>
<body>
<!-- Row 1 - Header -->
<header class="topBar">
<row>
<h1 class="pageTitle">Weather Dashboard</h1>
</row>
</header>
<div class="container-fluid">
<!-- Row 2 - Body -->
<div class="row">
<!-- Row 2, Column 1 - left side -->
<div class="col-sm-3">
<!-- Row 2, Column 1, Row a - City Search -->
<div class="row">
<div class="col-sm-12">
<div class="row searchTitle">
<div class="col-sm-12">
<h2 class="lead">Search for a City:</h2>
</div>
</div>
<div class="row searchArea">
<div class="col-sm-9">
<input type="text" class="searchCity" placeholder="Choose a city...">
</div>
<div class="col-sm-3">
<button type="submit" class="searchButton">
<i class = "fa fa-search"></i>
</button>
</div>
</div>
</div>
</div>
<!-- Row 2, Column 1, Row b - City List -->
<div class="row">
<div class="col-sm-11 listArea">
<table class="cityList">
<tr>
<th>Recent Searches</th>
</table>
</div>
<div class="col-sm-1">
</div>
</div>
</div>
<!-- Row 2, Column 2 - right side -->
<div class="col-sm-9 rightSide">
<!-- Row 2, Column 2, Row a - Current Weather -->
<div class="row">
<div class="col-sm-12">
<div class="weatherArea">
<p>weather area</p>
</div>
</div>
</div>
<!-- Row 2, Column 2, Row b - 5-day Forecast Title -->
<div class="row">
<div class="col-sm-12">
<div class="forecastTitle">
<h2 class="lead">5-Day Forecast:</h2>
</div>
</div>
</div>
<!-- Row 2, Column 2, Row c - 5-day Forecast Cards -->
<div class="row">
<div class="col-sm-12">
<div class="row cardArea">
<div class="col-sm-2.2">
<div class="card forecast-01">
<div class="card-body bg-info">forecast</div>
</div>
</div>
<div class="col-sm-0.25"></div>
<div class="col-sm-2.2">
<div class="card forecast-02">
<div class="card-body bg-info">forecast</div>
</div>
</div>
<div class="col-sm-0.25"></div>
<div class="col-sm-2.2">
<div class="card forecast-03">
<div class="card-body bg-info" id="cardBody">forecast</div>
</div>
</div>
<div class="col-sm-0.25"></div>
<div class="col-sm-2.2">
<div class="card forecast-04">
<div class="card-body bg-info">forecast</div>
</div>
</div>
<div class="col-sm-0.25"></div>
<div class="col-sm-2.2">
<div class="card forecast-05">
<div class="card-body bg-info">forecast</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Links to js libraries and external logic sheet -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="./assets/logic.js"></script>
</body>
</html>
解决方案
只需对您的代码进行一些小改动:https ://i.imgur.com/nr3yOY8.png
// Wait until Dom has completed loading
$(document).ready(function() {
// Testing that logic.js has been successfully linked to index.html.
console.log("logic.js is linked successfully");
// GLOBAL VARIABLES
// SELECTORS
// selectors for left side column
let searchCity = $(".searchCity");
let cityList = $(".cityList");
let searchButton = $(".searchButton");
let searchHistory = [];
// selectors for right side column
let weatherArea = $(".weatherArea");
let forecastArea = $(".cardArea");
// BUILDING FUNCTIONS
// When user clicks search button...
$(searchButton).click(function(event) {
event.preventDefault();
console.log("requesting weather data...");
//GET VALUE WHEN CLICKED
// VARIABLES for AJAX
let searchedCity = $(searchCity).val();
let queryURL = "https://api.openweathermap.org/data/2.5/forecast?q=" + searchedCity + "&appid=YOUR_KEY"
// I took out my key for this question
// Push user's search into variable array
searchHistory.push(searchedCity);
// If the search field is not blank... -- This if statement may be breaking my code, still testing
if (searchedCity != "") {
// Locally store searchHistory -- having issues getting this to work
localStorage.setItem("searchHistory", searchHistory);
// Request weather data from OpenWeatherMap API
$.ajax({
url: queryURL,
method: "GET",
dataType: "jsonp",
})
// When weather data response is returned...
.then(function(response) {
console.log(response);
// Display weather data in weatherArea
let weatherData = show(response);
$(weatherArea).html(weatherData);
// Display forecast data in forecastArea
let forecastData = "";
// For each item in response...
for (var i in response.list) {
if (i > 0 && response.list[i].dt_txt.indexOf("12:00") > -1) { //NOT indexof
// Create variable to contain forecast data
let forecastArray = [
"<div class = 'col-sm-2 day'>",
"<p>",
response.list[i].dt_txt.split(" ")[0],
"</p>",
"<img src = 'http://openweathermap.org/img/wn/" + response.list[i].weather[0].icon + "@2x.png'>", //CORRECTED THIS
"<p> Temp: ",
response.list[i].main.temp,
" degrees</p>",
"<p> Humidity: ",
response.list[i].main.humidity,
"%</p>",
"<p> Wind Speed: ",
response.list[i].wind.speed,//NOT response.list[i].main.wind.speed,
" mph</p>",
"</div>"
];
// Add forecast Data to forecastArray
forecastData += forecastArray.join("");
}
}
// Display forecast data in forecastArea
$(forecastArea).html(forecastData);
$(searchCity).val("");
});
}
// If the search field is empty...
else {
$(weatherArea).text("Search field can't be empty");
$(forecastArea).text("Search field can't be empty");
}
});
// function for showing the response data for the weather
function show(response) {
console.log("Showing Response: ", response);
return response.city.name + "<h3> (" + response.list[0].dt_txt.split(' ')[0] + ") </h3>" +
"<p class = 'lead'>Temp: " + response.list[0].main.temp + " degrees</p>" +
"<p class = 'lead'>Humidity: " + response.list[0].main.humidity + " %</p>" +
"<p class = 'lead'>Wind Speed: " + response.list[0].wind.speed + " mph</p>";
};
// Get searh history from local storage and display in cityList
function showHistory() {
let searchStorage = localStorage.getItem("searchHistory")
$(cityList).append("<tr>").append("<td>" + searchStorage + "</td>")
};
showHistory();
// Close of 'document.ready' function
});
推荐阅读
- java - 从员工表中获取层次结构员工 ID
- windows - 将 exe 和 msi 文件合并到一个安装程序中
- sql - Oracle SQL (PL/SQL) 中带有集合的窗口函数(超前/滞后)
- scala - Spark(scala API)中的时间戳格式和时区
- robotframework - python.exe 已停止工作,一个问题导致程序停止正常工作
- xml - 以编程方式更改非托管 Solr 架构
- node.js - 使用 JWT 令牌会话存储与本地存储的身份验证哪种身份验证是安全的以及如何
- c# - 根据下拉值设置 2 个日期选择器的最小日期和最大日期
- android - 从 Play 商店安装的 android 应用程序中的唯一签名/密钥
- batch-file - 使用正则表达式重命名批处理文件以匹配 4 位数年份