【发布时间】:2023-03-26 05:25:01
【问题描述】:
我正在从 OpenWeatherAPI 访问 JSON 数据。 URL 的正确格式是
http://api.openweathermap.org/data/2.5/weather?q=Chicago&APPID=34lkj349gga9s8dug9sd8hg
在哪里 ?q={city}&APPID={API_key}
假设我提供了 url、q 参数和 APPID 参数。我使用 $.getJSON 功能来检索 JSON 数据。 $.getJSON 是否知道 URL 是用 ?、= 和 & 格式化的,还是我必须用自己的参数写进去?目前我返回的只是 localhost/?
这是我写的短程序。很好地解释了我期望它如何工作。
// Here is how the final url should look:
// api.openweathermap.org/data/2.5/weather?q=Chicago&APPID=33lkr3jlfj39asdflk
var weatherSearch = '';
// weather-search is my html form id. On submit, send the input
// (which is city name) to the function getWeather.
$('#weather-search').submit(function(event) {
weatherSearch = $('#weatherQuery').val();
event.preventDefault();
getWeather(weatherSearch);
});
// getWeather has params q (city name), and APPID (API key).
function getWeather(weatherSearch) {
var params = {
q: weatherSearch,
APPID: '33lkr3jlfj39asdflk'
};
// This is the url that goes before the params.
url = 'http://api.openweathermap.org/data/2.5/weather/';
// Request data using url and params above.
// Does $.getJSON format the url properly?
$.getJSON(url. params, function(data) {
// Pass JSON data to showWeather function.
showWeather(data.items);
console.log(data.items);
});
}
function showWeather(weather) {
// Show JSON data (weather) in html div id="weatherResults"
$('#weatherResults').html(weather);
}
这是 JavaScript 引用的 html。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>weather</title>
<script src="/jquery.js"></script>
<script src="openweather.js"></script>
</head>
<body>
<form id="weather-search">
<input type="text" id="weatherQuery"></input>
<input type="submit" value="Submit"></input>
</form>
<div id="weatherResults">
</div>
【问题讨论】:
标签: javascript json