如何从此API中提取JSON数据?

时间:2016-12-28 00:35:24

标签: javascript jquery json api

我正在修改我使用不同API制作的天气APP。我遇到了一个问题,我无法从我从API获得的JSON中提取任何内容。我使用了错误的符号还是我的JSON实际上没有正确传递到我的JS脚本中?

本地计算机上的代码

$(document).ready(function () {

    var long;
    var lat;
    var currentCity;
    var currentState;
    var country;

    $.getJSON("https://crossorigin.me/http://ip-api.com/json", function (data_init) { //access RESTFUL geo location API & set lattitude.longitude
        lat = data_init.lat;
        long = data_init.lon;
        currentCity = data_init.city;
        currentState = data_init.region;
        country = data_init.country;

        $(".heading").append("<h2>" + currentCity + "," + currentState + "<br>" + country + "</h2>");

        var api = "https://crossorigin.me/https://api.darksky.net/forecast/1246aa267663e22a4e428e4b20f0df5b/" + lat + "," + long;
        //Access weather API
        console.log(api);
        console.log(currentCity);
        console.log(currentState);
        console.log(country);

        $.getJSON(api, function (data) {

            var iconCode = data.currently.icon; //get Icon from API related to current weather conditions

            $(".message").append("<h4 id='tempData'>Current Temperature: " + data.currently.temp + "&#8451</h4>");
            $(".message").append("<h4>Conditions: " + data.weather[0].main + "</h4>");
            $("#reveal").on('click', function () { //click button
                data.main.tempData //on click convert temperature to farenheight
            });
            $(".message").append("<img id='conditions' src=" + iconUrl + ">");

            $("#tempData").hover(function () {
                $(this).fadeToggle('slow', function () {});
            });
            console.log(data);
        });
    });
    //$("#reveal").on("click", function(){

    //});
});

2 个答案:

答案 0 :(得分:0)

我不知道您使用的API,但看起来您的回调不完整。

回调通常以这种格式编写:

$.getJson("your url", function (err, data) { ... })

您可能忘记在其上处理错误参数。

答案 1 :(得分:0)

答案:我访问JSON的语法不正确。我试图访问“Currently”这个属性。它应该是......

var iconCode = data.currently.icon; 
$(".message").append("<h4 id='tempData'>Current Temperature: "+data.currently.temperature+"&#8451</h4>");