我參加了freecodecamp課程,目前我被困在天氣應用程序zipline中。我打電話的API是OpenWeatherMap。對我來說,問題在於$ .getJson沒有返回數據,即使這個鏈接是正確的。我在$ .getJSON之外放置了警報,並且它工作正常。我將分享源代碼:
所有這些都是在codepen上完成的,如果你沒有看到html標籤是因爲codepen自己做的。 CSS也是這樣做的。
HTML
<head>
<title>Weather App</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<h1>Free Code Camp Zipline</h1>
<h2>Local Weather App!</h2>
<p id="latitude"></p>
<p id="longitude"></p>
<div id="weather"></div>
<footer>
<p>Copyright © Luis M. Alvarez 2016. All Rights Reserved</p>
</footer>
</body>
CSS
body {
margin: 0;
font-family: "Georgia";
}
h1, h2 {
text-align: center;
}
p {
font-size: 20px;
text-align: center;
}
的Javascript
$(document).ready(function(){
///Geolocation
//Find the geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$("#latitude").html("latitude: " + position.coords.latitude);
$("#longitude").html("longitude: " + position.coords.longitude);
///Weather API
//Setup for weather app
var key = "d160d975b9920be65fcf14313e95afb4";
var weatherNow = "http://api.openweathermap.org/data/2.5/weather?lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&APPID=" + key + "&units=metric";
//Get the weather
//Here alert does work
$.getJSON(weatherNow, function(data) { //Where weatherNow is on this line the alert works too example: $.getJSON(alert(weatherNow), function(data) {
//Here the alert doesn't work
alert(weatherNow);
});
});
};
});
評論被添加在這裏,所以他們不會混淆代碼。請詳細解釋爲什麼它不起作用以及如何使其工作。
鏈接項目: https://codepen.io/Zero720/pen/RoOwaw
http://openweathermap.org/current
如何使請求通過? –
@LuisAlvarez看起來他們只允許HTTPS付費用戶。 https://openweathermap.desk.com/customer/portal/questions/8166727-http-to-https你的Codepen看起來像HTTP一樣可訪問:http://codepen.io/Zero720/pen/RoOwaw – ceejayoz
但是人們已經完成它在這個頁面,它通過看例子項目:http://codepen.io/FreeCodeCamp/full/bELRjV –