我正在使用Wunderground天气API为我的学校项目制作一个天气网站。这是我用来获取JSON数据的代码:
$.getJSON("http://api.wunderground.com/api/<apikey>/conditions/q/" + wlocation + ".json", function(data){
alert(data);
});
<apikey>
是我放置API密钥的地方,而$
字符只是JQuery的快捷方式。
当我打开这个网页时,这是本地的,没有发布,没有弹出警告,我得到错误:
XMLHttpRequest cannot load http://api.wunderground.com/api/<apikey>/conditions/q/<myzipcode>.json. Origin null is not allowed by Access-Control-Allow-Origin.
在对这个错误做了一些研究之后,听起来我可能不得不创建一个web服务器。然而,对于这个项目,我们需要把它作为一个文件夹。html和其他"web文件"。是否有其他方法来做到这一点,或者我必须做一个web服务器?这个项目很快就要到期了,所以任何帮助都很感激!
是的,您可以使用JSONP。
我不确定是否Wunderground Weather API在JSON中有某种回调。但如果他们甚至jQuery getJSON
支持JSONP。
似乎你遇到了同源策略
下面是您在原始帖子(http://www.wunderground.com/weather/api/d/docs?d=resources/code-samples)中提供的链接的代码示例。他们使用JSONP。是的,就像@antyrat说的,这是CORS的问题。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/Your_Key/geolookup/conditions/q/IA/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
</script>