我正在努力在我的网页中显示来自weather API的数据。我正在使用localhost,我能够成功地执行各种控制台日志。
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Weather App</title>
</head>
<body>
<h1>Weather App</h1>
<h2>Choose Location</h2>
<span id="error"></span>
<input type="text" name="city" id="city" placeholder="City Name">
<button id="submitLocation">Find</button>
<div id="show"></div>
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/weather.js"></script>
</body>
</html>
weather.js
$(document).ready(function(){
$('#submitLocation').click(function(){
//get value from input field
var city = $("#city").val();
//check not empty
if (city != ''){
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric" + "&APPID=MYID",
type: "GET",
dataType: "jsonp",
success: function(data){
console.log(data);
console.log(data.weather[0].main);
console.log(data.main);
console.log(data.main.temp);
var information = show(data);
$("#show").html(information);
}
});
}else{
$('#error').html('Field cannot be empty');
}
});
})
function show(data){
return
"<h3>Current Weather: "+ data.main.temp +"</h3>" +
"<h3>Current Weather: "+ data.main.description +"</h3>";
// "<h3>Current Weather: "+ data.weather[0].main +"</h3>"
}
控制台日志返回以下内容:
的console.log(数据);
{coord: {…}, weather: Array(1), base: "stations", main: {…}, visibility: 10000, …}
base
:
"stations"
clouds
:
{all: 90}
cod
:
200
coord
:
{lon: -0.13, lat: 51.51}
dt
:
1522885800
id
:
2643743
main
:
{temp: 6.78, pressure: 1001, humidity: 70, temp_min: 5, temp_max: 8}
name
:
"London"
sys
:
{type: 1, id: 5091, message: 0.0044, country: "GB", sunrise: 1522906029, …}
visibility
:
10000
weather
:
[{…}]
wind
:
{speed: 8.2, deg: 270}
__proto__
:
Object
的console.log(data.weather [0]。主要);
Clouds
的console.log(data.main);
{temp: 6.78, pressure: 1001, humidity: 70, temp_min: 5, temp_max: 8}
humidity
:
70
pressure
:
1001
temp
:
6.78
temp_max
:
8
temp_min
:
5
__proto__
:
Object
的console.log(data.main.temp);
6.78
我没有收到任何错误,并且控制台日志正常工作我假设问题是我试图显示数据或可能是我忽略的语法错误?
提前谢谢。
答案 0 :(得分:0)
改变了这个:
function show(data){
return
"<h3>Current Weather: "+ data.main.temp +"</h3>" +
"<h3>Current Weather: "+ data.main.description +"</h3>";
// "<h3>Current Weather: "+ data.weather[0].main +"</h3>"
}
对此:
function show(data){
return "<h3>Current Weather: "+ data.main.temp +"</h3>" + "<h3>Current Weather: "+ data.weather[0].main +"</h3>";
我不确定是不是因为我添加了一个返回,额外的空格或制表符,但是当我将代码移到一行时它开始工作。