2014-04-04 41 views
0

我想打個電話給OpenWeatherMap使用JavaScript API這個URL[JS,JSON]打開天氣地圖API:JSON調用和分析,以JS變種

http://api.openweathermap.org/data/2.5/weather?lat=(here comes the lat for a variable)&lon=(lon from variable)

然後(也許jQuery的?)解析API輸出(它的JSON我認爲),以獲得

"main":"Clear" and "temp":271.997 

,並設置「主」和「溫度」變量js的變量,並將它們發送到innerHTML的。

請問有人可以製作腳本示例嗎?

感謝您的幫助和對不起壞英語。

回答

1

由於您解析的是另一臺服務器(非本地)上的json文件,因此您需要使用JSONP。基本上你使用ajax傳遞一個回調參數來打開天氣圖。這使您能夠使用腳本中的數據。

以下jquery將使用座標變量生成一個到json文件的鏈接,使用jsonp解析數據並在ID爲「weather」的web元素中顯示信息。

您很可能想要添加錯誤處理併爲訪問者創建數據的本地緩存,然後在緩存最近的時候加載緩存。我希望這能夠幫到你。

var lat=00.00 //latitude variable 
var long=00.00 //longitude variable 
var data_url="http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+""; 
//function to pull information out of the json file and stick it into an HTML element 
getWeather(function (data) { 
    var weather_html = data.weather[0].description + "nbsp;" + data.main.temp; 
    document.getElementById('weather').innerHTML = weather_html; 
}); 
// function to use jsonp to get weather information 
function getWeather(callback) { 
    $.ajax({ 
     dataType: "jsonp", 
     url: data_url, 
     success: callback 
    }); 
};