2013-02-20 59 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