Javascript 似乎没有处理 JSON api

问题描述 投票:0回答:2

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

 $(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);
      });
    });
  }
});
javascript jquery json openweathermap
2个回答
1
投票

我在编码时遇到了类似的问题。假设您在 FCC 上?

无论如何,尝试添加&callback=?到 API URL。您可能需要以 JSONP 而不是 JSON 的形式获取数据。

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


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

© www.soinside.com 2019 - 2024. All rights reserved.