2017-06-18 50 views
0

我剛開始學習API請求,並試圖使用API​​XU API調用顯示當前多倫多的天氣(這裏是文檔:https://www.apixu.com/doc/current.aspx),我不確定我做錯了什麼。來自APIXU的天氣API的問題

這裏是HTML:

<div class="weather"> 
    <h3>Toronto Weather Forecast</h3> 
    <ul style="margin: 0"> 
    </ul> 
</div> 

這裏是JS:

 // Weather API 
    function loadData() { 
     var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=XXXXXXXXXXXXXXXXX&q=Toronto"; 
    $.getJSON(weatherAPIXU, function(data) { 
     var list = $(".place ul"); 
     forecast = data.current; 
     list.append('<li>Temp: ' + forecast.temp_c + '°C</li>'); 
    }).error(function(e) { 
     $(".place").append('<p style="text-align: center;">Sorry!</p><p style="text-align: center;">Could Not Be Loaded</p>'); 
    }); 
}; 

$('.place').submit(loadData); 

一旦我知道如何通過JSON實現它,我想與knockout.js其綁定以及

所以,如果你可以給我建議,那將不勝感激。

+1

在這個鏈接它說如何處理ajax請求與淘汰賽:http://knockoutjs.com/documentation/json-data.html。另外Knockout貼圖插件可以幫助你(http://knockoutjs.com/documentation/plugins-mapping.html)。 –

+0

謝謝你的回覆!我還沒有進入這個映射,但感謝你的鏈接 - 我會研究它。現在我只是很好奇爲什麼我的JSON沒有加載到HTML中。因爲我可以在控制檯中看到結果。 –

回答

0

我仔細看了看,發現我根本沒有加載API。所以,對於那些可能有類似問題的人來說,這是一個可行的解決方案

$(document).ready(function loadData() { 
    var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=XXXXXXXXXXXX&q=Toronto"; 
    $.getJSON(weatherAPIXU, function(data) { 
     var forecast = data.current.temp_c; 
     var weather = $(".weather"); 
     weather.append(forecast + '° C'); 
    }).error(function(e) { 
     $(".weather").append('Sorry! Not Loaded'); 
    }); 
    $('.weather').submit(loadData); 
});