2013-02-20 58 views
0

我是JavaScript和jquery的新手......我一直在尝试编写一段简单的代码来使用天气api提醒当前温度。简单天气API当前温度不工作

这里是我到目前为止有:

<script src="http://code.jquery.com/jquery-1.9.1.js"/> 

<script> 
var my_city="Washington,USA"; 
var my_key="8b0642a6c7133932132002"; 
var no_of_days=2; 
// build URI: 
var uri="http://free.worldweatheronline.com/feed/weather.ashx?    q="+my_city+"&key="+my_key+"&format=json&no_of_days="+no_of_days+"&includeLocation=yes"; 
// uri-encode it to prevent errors : 
uri=encodeURI(uri); 

jQuery.get(uri,function(r){ 
current_temp_C =r.data.current_condition[0].temp_C; 
alert(current_temp_C); 
},"json"); 
</script> 

然而,什么也不显示。如果有人能指出我要出错的地方,请告诉我! 谢谢!

+0

有迹象表明,有演示代码等资源进行天气http://codepen.io/jamesfleeting/笔/ wHism – Shanimal 2013-02-20 14:05:09

+0

很棒的演示Shanimal,但我更多的是针对当前温度的文本。谢谢! – InfiniDaZa 2013-02-20 14:13:28

+0

下面是另一个http://codepen.io/anon/pen/bvyDh – Shanimal 2013-02-20 14:13:47

回答

2

我假设你在错误处理程序中结束了,并且你只是在代码中关注成功的ajax调用。由于您使用jQuery> 1.5,你可以做这样的事情来检查:

jQuery.get(uri,function(r){ 
    current_temp_C =r.data.current_condition[0].temp_C; 
    alert(current_temp_C); 
},"json").fail(function(jqXHR, ajaxOpts, thrownError){ 
    alert(thrownError); 
}); 

此外,您查询字符串有根据的代码有很多的空间。而不是将数据作为查询字符串定制的,一个对象常量数据作为第二ardument添加到$.get

jQuery.get(uri, { key1: 'value1', key2: 'value2' }, function(r){ 
//etc... 
+0

我试过所有这些,但仍然没有运气:(谢谢! – InfiniDaZa 2013-02-20 14:20:45

+0

@InfiniDaZa如果你详细说明“没有运气”,我可以试着帮你 – Johan 2013-02-20 14:48:30

+0

对不起,只是我现在有一个新的脚本工作。对不起 – InfiniDaZa 2013-02-20 16:06:47