从URL检索和显示JSON数据

时间:2012-05-09 16:25:47

标签: javascript jquery ajax json

我正在尝试使用javascript和URL请求从JSON对象检索和显示有关当前天气的信息:

http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805'

来自URL的数据如下所示:

   {
    "data": {
        "current_condition": [
            {
                "cloudcover": "75",
                "humidity": "88",
                "observation_time": "03:30 PM",
                "precipMM": "2.7",
                "pressure": "1008",
                "temp_C": "12",
                "temp_F": "54",
                "visibility": "8",
                "weatherCode": "302",
                "weatherDesc": [
                    {
                        "value": "Moderate rain"
                    }
                ],
                "weatherIconUrl": [
                    {
                        "value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0018_cloudy_with_heavy_rain.png"
                    }
                ],
                "winddir16Point": "SE",
                "winddirDegree": "140",
                "windspeedKmph": "17",
                "windspeedMiles": "11"
            }
        ],
        "request": [
            {
                "query": "DE3",
                "type": "Postcode"
            }
        ],
        "weather": [
            {
                "date": "2012-05-09",
                "precipMM": "11.8",
                "tempMaxC": "13",
                "tempMaxF": "56",
                "tempMinC": "12",
                "tempMinF": "53",
                "weatherCode": "266",
                "weatherDesc": [
                    {
                        "value": "Light drizzle"
                    }
                ],
                "weatherIconUrl": [
                    {
                        "value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0017_cloudy_with_light_rain.png"
                    }
                ],
                "winddir16Point": "SE",
                "winddirDegree": "141",
                "winddirection": "SE",
                "windspeedKmph": "12",
                "windspeedMiles": "7"
            },
            {
                "date": "2012-05-10",
                "precipMM": "11.1",
                "tempMaxC": "18",
                "tempMaxF": "64",
                "tempMinC": "6",
                "tempMinF": "43",
                "weatherCode": "353",
                "weatherDesc": [
                    {
                        "value": "Light rain shower"
                    }
                ],
                "weatherIconUrl": [
                    {
                        "value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0009_light_rain_showers.png"
                    }
                ],
                "winddir16Point": "SSW",
                "winddirDegree": "209",
                "winddirection": "SSW",
                "windspeedKmph": "30",
                "windspeedMiles": "19"
            }
        ]
    }
}

我已经尝试了几个脚本来尝试获取数据并取出位以显示在div中。第一个看起来像这样:

   $.ajax({
    url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805"
    dataType: 'json',
    success: function(data) {
        jQuery.each(data, function() {
            alert("HELLO");
            alert("Current Cloud Cover = " + this.data.current_condition.cloudcover);
            alert("Current Humidity = " + this.data.current_condition.humidity);
        });
    }
});

第二个看起来像这样:

var postcode = document.getElementById("address").value;

function getWeather(userName, count) {

   $.getJSON(
     'http://free.worldweatheronline.com/feed/weather.ashx?q' + postcode + '&format=json&num_of_days=2&key=ec9c2dc5ba201904120805', 
     {}, 
     showWeather,
    //'jsonp'
  );

}

function showWeather(day) {

    var str = '<ul>';
    str += '<h2>Tweets from ' + postcode + '</h2>';
    var i = 0;
    $.each(day, function(index, value) {
        if (i == count) return;
        var dt = new Date(value.date);
        str += '<p>';
        str += value.temp_C; //gets "text" from JSON
        str += '</p>';
        str += '';
        str += '';
        i++;
    });
}

我想从JSON URL获取天气信息并在div中显示一些信息,任何人都可以解释如何执行此操作这两个脚本不起作用。

2 个答案:

答案 0 :(得分:6)

$.ajax({
    url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805",
    dataType: 'jsonp',  // You  need to use 'jsonp' here because it is cross domain request 
    success: function(data) {
        $.each(data, function(index, value) {
            alert(value.current_condition[0].cloudcover);
            alert(value.current_condition[0].humidity);
            alert(value.current_condition[0].weatherDesc[0].value);
            alert(value.request[0].query);
            alert(value.request[0].query);
            $.each(value.weather, function(i, val) {
                alert(val.precipMM);
                alert(val.weatherDesc[0].value);
            })
        });
    }
});

<强> DEMO

答案 1 :(得分:2)

存在一些问题......以下内容应该有效(修改第一个代码块)。

$.ajax({
    url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805&callback=?",
    dataType: 'jsonp',
    success: function(data){
        jQuery.each(data, function(){
            alert(JSON.stringify(this));
            alert("Current Cloud Cover = " + this.current_condition[0].cloudcover);
            alert("Current Humidity = " + this.current_condition[0].humidity);
        });
    }
});

回顾一下:

  1. 您需要使用 JsonP 来规避跨网站脚本限制(通过在AJAX网址中添加“&amp; callback =?”来实现这一点。
  2. JSON响应的根目录是数据,因此您需要编写data.data。
  3. current_condition 属性是一个数组 - 必须添加一个索引器(即[0])才能访问它。