node.js:雅虎天气的jQuery插件不打印数据
我得到了node.js与jQuery和这个插件: http : //simpleweatherjs.com/ 。 现在我想使用另一个服务的天气数据,而不是把它放到HTML中,但我不能访问/打印数据。 错误function起作用,成功function不起作用。
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
还有一个插件的节点模块,但是我不知道如何使它工作,没有文档。
我build议不要使用jQuery插件,而是直接使用底层数据。
Simpleweather使用雅虎API来检索天气信息。
为了以易于使用的JSON格式获取天气信息,您可以使用雅虎的查询语言
1.获取位置ID
例如,如果我想获得“瑞典斯德哥尔摩”的天气信息,我可以查询
SELECT woeid FROM geo.places where text="Stockholm, Sweden" LIMIT 1
这将返回"woeid": "906057"
[执行YQL]
2.获取天气信息
现在是时候使用我们在上一步中检索到的位置ID。
SELECT item.condition.temp FROM weather.forecast WHERE woeid = 906057
这将返回"temp": "81"
[执行YQL]
自动化
为了程序节点接收温度,我build议使用请求模块。 您可以从查询构build器页面复制API endopint。 在这个例子中是这样的
我想你可以很容易地从这里出发,但是为了完整起见,我会包含一个简单的节点示例:
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); });
jsdom没有实现XMLHttpRequest。 看到这个问题可能的解决scheme。