Wunderground Api用户输入他们的位置以获取他们的位置temp

时间:2014-11-15 15:56:46

标签: jquery ajax json

我试图让用户输入他们当前的位置,即:利兹,曼彻斯特,伦敦等,我正在尝试获取一个警报,显示他们输入的区域的当前温度,但是我可以& #39;得到任何展示。难道我做错了什么?

<h3> Weather Data </h3>
<form method="POST" action="about.php">
    <!-- user inputs their location here  -->
    <input type="text" name="location" value= "Country"/>
    <input type="text" name="city" value='City'/>
    <input type="submit" name="submit" value="submit" />
</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

<script>
jQuery(document).ready(function($) {
    $.ajax({
        url : "http://api.wunderground.com/api/5e8af95dbdebbd73/geolookup/conditions/forecast/q/UK/England.json",
        dataType : "jsonp",
        success : function(parsed_json) {
            var location = parsed_json['location']['city'];
            var temp_f = parsed_json['current_observation']['temp_f'];
            alert("Current temperature in " + location + " is: " + temp_f);
       }
    });
});
</script>

上面的脚本执行临时函数

1 个答案:

答案 0 :(得分:0)

对wunderground的API调用没有返回你认为的结构,这是调用返回的对象之一。

{
 city: "Aberdaron",
 country: "UK",
 country_iso3166: "GB",
 country_name: "United Kingdom",
 l: "/q/zmw:00000.1.03405",
 name: "Aberdaron",
 state: "",
 zmw: "00000.1.03405"
}

如您所见,没有天气数据。

当您为天气数据获得正确的API调用时,此代码可以帮助您。

See the working Demo

(function () {
    var city_data;
    // don't wait for the document to load to get the city data.
    (function () {
        $.ajax({
            url: /* the same from the question */,
            dataType: "jsonp",
            success: function (parsed_json) {
                // build the map in a tmp variable as we don't want
                // city_data to be partially initialized.
                var tmp = {};
                $.each(parsed_json.response.results, function (key, val) {
                    // map the city name to its data
                    tmp[val.city] = val;
                });
                city_data = tmp;
            }
            // todo handle errors
        });
    }());

    jQuery(document).ready(function ($) {

        // on page load register the on form submit call back
        $('form').submit(function (e) {
            e.preventDefault();

            // the api call has not finished yet
            if (city_data === undefined) {
                alert("Sorry no city data yet");
                return;
            }

            // get the value in the text box
            var city = $('[name="city"]', this).val();
            if (city_data.hasOwnProperty(city)) {
                alert(city_data[city].country_name);
            } else {
                alert(city + " was not found");
            }
        });
    });
}()); // execute immediately