【问题标题】:node.js: jQuery plugin for Yahoo weather doesn't print datanode.js:Yahoo 天气的 jQuery 插件不打印数据
【发布时间】:2014-08-05 13:50:59
【问题描述】:

我让 node.js 与 jQuery 和这个插件一起工作:http://simpleweatherjs.com/。现在我想将天气数据用于另一个服务,而不是将其放入 HTML,但我无法访问/打印数据。错误函数有效,成功函数无效。

var jsdom = require("jsdom");
jsdom.env({
  html: '<html><body><div id="weather"></div></body></html>',
  scripts: [
    'http://code.jquery.com/jquery-2.1.1.min.js',
    'http://cdnjs.cloudflare.com/ajax/libs/jquery.simpleWeather/3.0.2/jquery.simpleWeather.min.js'
  ],
  done: function(errors, window) {
    var $ = window.jQuery;

    $.simpleWeather({
        location: 'Paris',
        woeid: '615702',
        unit: 'c',
        success: function(weather) {
            console.log(weather.temp+'°'+weather.units.temp);
        },
        error: function(error) {
            console.log(error.message);
        }
    });
  }
});

这就是它正常的样子http://codepen.io/fleeting/pen/xwpar

插件也有一个节点模块,但我不知道如何让它工作,也没有文档。

【问题讨论】:

    标签: javascript jquery node.js yahoo weather


    【解决方案1】:

    我建议不要使用jQuery插件,而是直接使用底层数据。

    Simpleweather 使用 yahoo API 来检索天气信息。

    为了以易于使用的 JSON 格式获取天气信息,您可以使用 yahoo 的查询语言

    1.获取位置 ID

    例如,如果我想获取“瑞典斯德哥尔摩”的天气信息,我可以查询

    SELECT woeid FROM geo.places where text="Stockholm, Sweden" LIMIT 1
    

    这将返回 "woeid": "906057" [Execute YQL]

    2。获取天气信息

    现在可以使用我们在上一步中检索到的位置 ID。

    SELECT item.condition.temp FROM weather.forecast WHERE woeid = 906057
    

    这将返回"temp": "81" [Execute YQL]

    自动化

    为了以编程方式接收节点中的温度,我建议使用request 模块。您可以从查询构建器页面复制 API endopint。在这个例子中它是

    https://query.yahooapis.com/v1/public/yql?q=SELECT%20item.condition.temp%20FROM%20weather.forecast%20WHERE%20woeid%20%3D%20906057&format=json

    我想你可以很容易地从这里开始,但为了完整起见,我将包含一个简单的节点示例:

    var request = require('request');
    var url = 'https://query.yahooapis.com/v1/public/yql?q=SELECT%20item.condition.temp%20FROM%20weather.forecast%20WHERE%20woeid%20%3D%20906057&format=json';
    
    request(url, function (err, resp, body) {
        if (err || resp.statusCode != 200)
            return console.log('Could not get weather information');
        var json = JSON.parse(body);
        console.log('Temperature in Stockholm:', json.query.results.channel.item.condition.temp);
    });
    

    【讨论】:

    • 这简直太完美了。非常感谢!我不知道 Yahoo API 可以做到这一点。
    • 没问题,很高兴能帮上忙。顺便说一句,我相信有一些 YQL 节点模块,因此您可以进一步简化示例,但我不熟悉它,所以我会让您测试一下
    【解决方案2】:

    jsdom 没有实现 XMLHttpRequest。有关可能的解决方案,请参阅this 问题。

    【讨论】:

      猜你喜欢
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      相关资源
      最近更新 更多