代码之家  ›  专栏  ›  技术社区  ›  Jio

无法从Weather Underground API解析JSON响应

  •  0
  • Jio  · 技术社区  · 9 年前

    我正在尝试创建一个简单的天气页面。我想从weather Underground API检索用户位置的坐标,然后检索位置的天气信息。我可以看到我坐标的JSON响应。然而,我在使用AJAX函数解析JSON并在HTML上显示它时遇到了问题。下面是我的代码

    HTML:

    <div class="container-fluid text-center">
    <body>
    <div id="forecast">
    <h1>Weather at <span id="location"> </span></h1>
    <div id="imgdiv">
    <img id="img" src=""/>
    </div>
    <p>It is currently <span id="temp"> </span>°C with <span id="desc"> </span></p>
    <p>Wind: <span id="wind"></span></p>
    
    </body>
    </div>
    

    JQuery;

        var Geo={};
         var temp_f
            //var key = ‘4d6eb96f1aa092b2’;
    
            if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(success,error);
            }
            else {
            alert('Geolocation is not supported');
            }
    
            function error() {
            alert("That's weird! We couldn't find you!");
            }
    
       function success(position) {
                  Geo.lat = position.coords.latitude;
                  Geo.lng = position.coords.longitude;
                  Geo.url   = "http://api.wunderground.com/api/4d6eb96f1aa092b2/forecast/geolookup/conditions/q/" + Geo.lat + "," + Geo.lng + ".json"; 
    
         $.ajax({
        url : Geo.url,
        dataType : "json",
        success : function(url) {
             location = url['location']['city'];
             temp_f = url['current_observation']['temp_f'];
            $("#temp").html(temp_f);
        }
       });
    
    }
    

    我得到的位置和temp_f值为 undefined 我提到了一个非常相似的帖子 Weather Underground API with Ajax 但却不知道问题是什么?我是新的,所以请原谅,如果我错过了一些基本的东西。

    1 回复  |  直到 9 年前
        1
  •  1
  •   Jigarb1992    9 年前

    它对我很好检查: https://jsfiddle.net/jigarb1992/q1w8usq9/

    我在你的代码中发现的问题可能在这里 location = url['location']['city']; 这个 location 在里面 javascript 将重定向您到给定位置。

    尝试我在其中进行更改的代码 JSIDLE