Javascript似乎没有处理JSON api

时间:2016-05-08 03:33:47

标签: javascript jquery json api openweathermap

我试图制作一个使用openweathermap api的页面来显示用户的城市和当地温度,不幸的是它似乎没有处理JSON api并且什么都不做。据我所知,我的代码很好,所以我不明白什么是错的。
这里是jsfiddle链接和javscript代码:
https://jsfiddle.net/qo2h1L9e/2/

function get_immediate_children_for(element, array_of_children) {
    $(element).children().each(function() {
        if (this.tagName == "SOMETHING") {
            array_of_children.push(this);
        }
        else {
            get_immediate_children_for(this, array_of_children);
        }
    });
}

2 个答案:

答案 0 :(得分:1)

编码时我遇到了类似的问题。假设你在使用FCC?

无论如何,尝试添加& callback =?到api URL。您可能需要将数据作为JSONP而不是JSON获取。

此外,您无需定义数据。您可以通过json参数直接访问该对象。

答案 1 :(得分:0)

我已经完成了jQuery尝试此代码

        $(document).ready(function() {
            var data;
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    var lat = position.coords.latitude;
                    var lon = position.coords.longitude;
                    console.log(lat);
                    console.log(lon);
                    console.log("api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=4907e373098f091c293b36b92d8f0886");
//                    $.getJSON("api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=4907e373098f091c293b36b92d8f0886", function(json) {
//                        data = json;
//                        console.log(data.name);
//                        $("#city").text(data.name);
                    //                    });
                    var url = 'http://api.openweathermap.org/data/2.5/weather';
                    var params = {};
                    params.lat = lat;
                    params.lon = lon;
                    params.APPID = "4907e373098f091c293b36b92d8f0886";

                    $.ajax({
                        type: "GET",
                        url: url,
                        dataType: "jsonp",
                        contentType: "application/json; charset=utf-8",
                        data: params,
                        success: function (res) {
                            console.log(res);
                        },
                        error: function (res) {
                        }
                    });


                }
                );
            }
        });

问题出在json。对于跨域使用jsonp