【发布时间】:2018-07-30 16:51:38
【问题描述】:
我想使用 Knockout 数据绑定来更新我的 html div 元素中的天气 API 数据。目前,我正在使用 jQuery 来更新 DOM,但我更喜欢使用 Knockout。我还想动态更改位置 zip,以便天气特定于我的 div 中的那个位置。我有一个位置数组。
这是我的代码: html:
var zip = locations[0].zipcode;
var myOpenWeatherAPIKey = 'xxxxxxxxxxxxxxxxxxxx';
var openWeatherMapUrl = "http://api.openweathermap.org/data/2.5/weather?zip=" + zip + ",us&APPID=" + myOpenWeatherAPIKey + "&units=imperial";
console.log(zip);
//using JSON method for retrieving API data
$.getJSON(openWeatherMapUrl, function(data) {
var parameters = $(".weather-data ul");
var iconCode = data.weather[0].icon;
var iconDescription = data.weather[0].main;
var iconUrl = "http://openweathermap.org/img/w/" + iconCode + ".png";
detail = data.main;
windspd = data.wind;
parameters.append('<li>Temp: ' + Math.round(detail.temp) + '° F <br></li>');
parameters.append('<li><img style="width: 25px" src="' + iconUrl + '"> ' + iconDescription + '</li>');
}).fail(weatherError = function(e) {
$(".weather-data").append("OpenWeatherAPI is unable to load!");
});
<div id="open-weather" class="open-weather">
<div id="weather-data" class="weather-data">
<p> <br> Current Weather</p>
<ul id="weather-items" class="weather-items">
</ul>
</div>
</div>
谢谢,
【问题讨论】:
标签: json api knockout.js binding