使用 JQuery/Ajax 从 API 检索数据

retrieving data from API using JQuery/Ajax

我正在尝试从 openweathermap api 获取信息到我的应用程序中。我尝试使用 ajax 来获取数据,但它显示为未定义。

   $(function(){

        var $temp = $('#temperature');
        var $humidity = $('#humidity')
        temp = document.getElementById("temperature");
        $.ajax({
            type: 'GET',
            url: 'http://api.openweathermap.org/data/2.5/weather?q={' +
                  markers["title"] + '}&APPID=' + APPID,
            success: function(data){
              console.log('success', data);
              $temp.append(data.main.temp);
              $humidity.append(data.main.humidity);
            }

        });

      });

  var contentString = '<div id="content">'+
      '<div id="siteNotice">'+
      '</div>'+
      '<h1 id="firstHeading" class="firstHeading">' + markers["title"] + '</h1>'+
      '<div id="bodyContent">'+
      '<div class = "temperature"><span id = "temperature"> '+ temp +' </span>&degC</div>' +
      '<div class = "humidity">'+ humidity +'<span id = "humidity"></span>%' +
      '</div>';`

您需要 JSON.parse() 您的数据。 $ajax 可能会返回一个字符串,因此您需要先解析数据,然后才能从中获取属性。

您收到未定义错误的原因是您无法检索字符串的属性。

按地理坐标:

        var apiUrl = "http://api.openweathermap.org/data/2.5/find?lat=" + latitude + "&lon=" + longitude + "&units=imperial&cnt=7&appid=" + APIkey;

使用地理定位提供纬度和经度值。

或仅提供城市 ID

var apiUrl = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=' + APIkey;