简体   繁体   English

使用JQuery / Ajax从API检索数据

[英]retrieving data from API using JQuery/Ajax

在此处输入图片说明

I am trying to get the information from openweathermap api into my app. 我正在尝试将openweathermap api中的信息获取到我的应用程序中。 I tried using ajax to get the data, but it is shown as undefined. 我尝试使用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>';`

You need to JSON.parse() your data. 您需要JSON.parse()您的数据。 $ajax is likely returning a string, so you need to parse the data before you can get properties out of it. $ ajax可能返回一个字符串,因此您需要先解析数据,然后才能获取其属性。

The reason you are getting an undefined error is because you can't retrieve properties of a string. 出现未定义错误的原因是因为无法检索字符串的属性。

By geographic coordinates : 按地理坐标:

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

Use the geolocation to provide values for latitude and longitude. 使用地理位置来提供纬度和经度的值。

or simply provide City Id's 或只是提供城市ID

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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