简体   繁体   中英

How do I pull JSON data from this API?

I'm reworking a weather APP I made using a different API. I've run into an issue where I can't pull anything from the JSON i get from said API. Am I using the wrong notation or is my JSON not actually being passed into my JS script correctly?

Code on my local machine

$(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(){

    //});
});

I don't know what API you are using, but it looks like your callback is incomplete.

Callbacks are usually written in this format:

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

You probably forgot to handle err parameter on it.

Answer: My syntax for accessing the JSON was incorrect. I was trying to access the property 'Currently'.It should be...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM