在jQuery中选择和显示api数据

时间:2018-01-25 18:53:25

标签: javascript jquery api openweathermap

我试图从openweathermap API显示天气预测数据 - 当我运行此代码并单击我的提交按钮时,它会显示" undefined"在我的页面上。

var api_key = "&APPID=c0aa3c8995df1b0dd97032d0072333b3";
var api = "http://api.openweathermap.org/data/2.5/forecast?q=";
var city = "Toronto";
var units = "&units=metric"

$( "#submit" ).click(function() {
    input = $('#city');
    $(function(){
        var url = api + input.val() + api_key + units;
        $.getJSON(url, function(wd){
            document.write(JSON.stringify(wd.list.main));
        })
    })
});

1 个答案:

答案 0 :(得分:1)

List是一个数组,您应该像这样访问它

wd.list[0].main.temp

此外,不需要使用stringify,这对我来说很好

document.write(wd.list[0].main.temp);

这是一个循环,请参阅this fiddle

var api_key = "&APPID=c0aa3c8995df1b0dd97032d0072333b3";
var api = "https://api.openweathermap.org/data/2.5/forecast?q=";
var units = "&units=metric"

$( "#submit" ).click(function() {
    input = $("#city");
    $(function(){
        var url = api + input.val() + api_key + units;
        $.getJSON(url, function(wd){
            var list = wd.list;
            $.each(list, function(i,v) {
                 document.write("Timestamp: " + v.dt + " " + "Temp: " + v.main.temp + " " + "Min: " + v.main.temp_min + " " + "Max: " + v.main.temp_max + " " + "Pressure: " + v.main.pressure + "<br />");
            });
        })
    })
});