如何处理json响应并显示div中的值

问题描述:

我使用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数据中显示哪些数据? –

您可以访问这些数据你有作为一个对象。在你的情况下,该对象将如下所示。

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) });