【问题标题】:Weather forecast from WOEID (using YQL or rss) in javascript?javascript中WOEID(使用YQL或rss)的天气预报?
【发布时间】:2012-03-13 07:03:52
【问题描述】:

有没有什么方法可以从 woeid 在 javascript 中获取天气预报?

我尝试使用 yahoo 的 rss 提要,但无法使用。这是我的代码

    var url = "http://weather.yahooapis.com/forecastrss?w=" + encodeURIComponent('WOEID here');

    $.ajax({
        url: url,
        dataType: 'jsonp',
        jsonpCallback: function(data) { console.log(data); },
        success: function(data) { alert("success"); }
    });

有什么建议吗?

【问题讨论】:

    标签: javascript jquery yql weather yahoo-api


    【解决方案1】:

    这是使用 jQuery 和 YQL 获取所需信息的最简单方法:

    var woeid = "26355493";
    
    var $url = "http://query.yahooapis.com/v1/public/yql?callback=?";
    
    $.getJSON($url, {
        q: "select * from xml where url=" +
           "\"http://weather.yahooapis.com/forecastrss?w=" + woeid + "\"",
        format: "json"
      }, function (data) {
        console.log(data.query.results.rss.channel);
      }
    );​
    

    The query in the YQL console...

    The JavaScript code in jsfiddle...

    【讨论】:

    • 这不会返回完整的天气信息。您如何使用它获取湿度、大气数据等?
    • 好的,我更新了代码,为您将所有数据输出到调试控制台。 YQL 和 jsfiddle 链接也已更新。在进行这些更改时,我发现select * from rss 实际上只返回了与select * from xml 相比的数据子集,所以我也进行了更改。
    • 太棒了!真的帮助我快速解决问题。我的投票 +1
    【解决方案2】:

    显然,Weather API 以RSS 格式返回其结果,而您的函数期望它们以jsonp 格式返回。考虑使用Yahoo! Pipes 为您获取天气RSS 提要,对其进行处理,然后以jsonp 格式返回。

    这是一个做类似事情的管道:

    http://pipes.yahoo.com/pipes/pipe.info?_id=4d160cd8ed9d6d78164213928a51507d

    【讨论】:

      【解决方案3】:

      按照龙的建议,我创建了一个 Yahoo Pipe - 这是我的完整代码;代码中的 url 是我创建的 Yahoo Pipe。

      $(function(){
         var url = "http://pipes.yahoo.com/pipes/pipe.run?_id=e33143abd20b19a0173b3a4b479fa4d3&_render=json&w=YOURWOEIDHERE";
      
         function createRequest() {
             try { return new XMLHttpRequest(); } catch(e) {}
             try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
             return null;
         }
         var request = createRequest();
         request.open("GET", url, true);
         request.onreadystatechange = callback;
         request.send(null);
      
         function callback() {
             if(request.readyState != 4) { return }
             Obj = $.parseJSON(request.responseText);
             console.log(Obj);
         }
      });
      

      参考:
      雅虎管道:http://pipes.yahoo.com/pipes/pipe.info?_id=e33143abd20b19a0173b3a4b479fa4d3
      jQuery 1.5 - JSON error invalid label

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-16
        • 2020-05-30
        • 2013-06-22
        • 2016-06-10
        • 1970-01-01
        • 1970-01-01
        • 2011-11-15
        相关资源
        最近更新 更多