我目前在使用 Mootools 的 JavaScript 中使用 Google 天气 API 时遇到困难。
我正在使用这样的代码:
var location = $('weather-location').value;
var req = new Request({
url: 'http://www.google.com/ig/api?weather=' + location,
method: 'get',
onSuccess: function(responseText, responseXML)
{
responseXML.getElements('forecast_information').each(function(item)
{
item.getElements('city').each(function(city_data)
{
$('placename').set('html','Weather for ' + city_data.get('data'));
});
});
}
}).send();
此代码导致浏览器错误,在 Firebug 中报告为:
"NetworkError: 405 Method Not Allowed - http://www.google.com/ig/api?weather=72601&location=72601"
据我所知(我对此很陌生),这个问题是由跨域访问冲突引起的。
我试过了:
1)使用'post'而不是'get'作为方法......类似的结果
2) 使用 Request.HTML 和 Request.JSON 而不是 Request... 类似的结果
3)使用 Request.JSONP ...不同的错误(我认为是文档格式)。我怀疑这是因为谷歌天气 API 返回直接 XML 并且没有设置为提供 JSONP。
4) 使用 YQL 而不是直接访问 google 的 URL(示例 URL:http : //query.yahooapis.com/v1/public/yql?q=select%20 *%20from%20xml%20where%20url%3D"http% 3A%2F%2Fwww.google.com%2Fig%2Fapi%3Fweather%3DDenver%2520CO") ...这没有错误,但也没有返回任何结果(如果输入浏览器地址,URL 确实有效)。
我能够让它工作的唯一方法是拉天气 XML 服务器端并通过代理将其提供给浏览器。但是,我想在不增加服务器负担的情况下完成此操作。
如何才能做到这一点?