简体   繁体   中英

how to handle json response and display the values in a div

I am using openweather api to get weather data.when i enter the city name the server returns a json data I need to know how to handle the data and i need to display the data inside a 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> 

You can access the data You got as an object. In your case the object will be as shown below.

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

}

You can access it script itself as shown below.

$.getJSON(url, function (data) { $('#disp').html('Temperature:' + data.main.temp + 'deg Fahrenheit' + 'Pressure:'+ data.main.pressure) });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM