用于创建天气预报应用程序的多个Ajax请求

时间:2016-02-26 15:23:48

标签: javascript jquery ajax asynchronous

我正在构建天气预报应用程序,我完成了HTML和CSS编码,因此在我的应用程序中我有6个不同的城市,我想输出以下信息:当前温度,当前天气的图标,时区等等。到目前为止一切正常,但我想学习如何而不是制作6个不同的$ .ajax GET请求,只为所有6个城市创建一个,并从输出JSON对象中获取所需的信息。在我的天气应用程序中,我有HTML按钮,允许用户点击并更改当前城市。

我正在使用The Dark Sky Forecast API服务,以下是我如何构建我的某个城市的GET请求。

function getWeatherContent(callback) {
    $.ajax({
        type: 'GET',
        url: 'https://api.forecast.io/forecast/02eb002028b663d6a8784ae534127171/35.685,139.7513889',
        async: false,
        dataType: 'jsonp',
        success: function(data){
            callback(data);
        }
    });
}

// Adding Information from our Ajax request.

getWeatherContent(function(details){
    console.log(details);

    // Take the current Temp from currently object and from Farenh transform it to Cels temp.
        var currentTemperature = details.currently['temperature'];

    // Calculate F to C by using JavaScript formula -> C = (F- 32) * (5/9).
    // Round the value to nearest integer.
        var celsFormula = Math.round((currentTemperature - 32) * (5/9));


    // Append Real-Time Degree to an HTML
        $('.degree').html('<p>' + celsFormula + '&deg;C' + '</p>');


});

0 个答案:

没有答案