2016-05-30 27 views
0

我使用openweather api來獲取天氣數據。當我輸入城市名稱時,服務器返回一個json數據我需要知道如何處理數據,我需要顯示數據的DIV中如何處理json響應並顯示div中的值

function loadweather() { 
 
    var q = document.getElementById("in").value; 
 
    var appid = document.getElementById("appid").value; 
 
    var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + q + '&appid=' + appid; 
 
    $.getJSON(url, function(data) { 
 
    console.log(data) 
 
    }); 
 
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> 
 

 
<input type="text" id="in" value="New Delhi"/> 
 
<input type="hidden" id="appid" value="086a3e2bd775aac95a9b096b5233f049"> 
 
<button id="go" onclick="loadweather()">Search</button> 
 
<div id="disp"></div>

+0

需要顯示哪些數據?即'data.weather.main'會取到你''Haze' – Satpal

+0

'console.log(data)'打印你想要的? – messerbill

+0

您可以使用JSON.parse(data)方法來訪問json值。順便說一下你需要從json數據中顯示哪些數據? –

回答

0

您可以訪問這些數據你有作爲一個對象。在你的情況下,該對象將如下所示。

public class RootObject 
{ 
public Coord coord { get; set; } 
public List<Weather> weather { get; set; } 
public string @base { get; set; } 
public Main main { get; set; } 
public int visibility { get; set; } 
public Wind wind { get; set; } 
public Clouds clouds { get; set; } 
public int dt { get; set; } 
public Sys sys { get; set; } 
public int id { get; set; } 
public string name { get; set; } 
public int cod { get; set; } 

}

您可以訪問它腳本本身,如下圖所示。 $('#disp')。html('Temperature:'+ data.main.temp +'deg Fahrenheit'+'壓力:'+ data.main(012)。 .pressure) });