提问者:小点点

OpenWeather API紫外线指数


使用OpenWeather API,我需要使用纬度和经度找到UV指数。 我需要弄清楚如何从queryURL请求中获取信息,以便能够在我的html文件上显示该值。 我知道我的代码缺少了什么,只是不确定是什么。 现在我正在使用一个“预测”查询URL并查看我想搜索的城市的LAT/LON,我只需要使用该信息创建另一个请求。 当我运行代码时,我得到以下错误:“response.city.coord is not a function”。 这是我到目前为止得到的代码:

    var lat = "response.city.coord"("lat");
    var lon = "response.city.coord"("lon");

    var apiKey1 = "ada1f715672a438e9b9acaa7ea0e930b";
    var queryURL2 = `https://api.openweathermap.org/data/2.5/uvi?appid=${apiKey1}&lat=${lat}&lon=${lon}`;

    $.ajax({
        url: queryURL2,
        method: "GET",
    }).then(function (res) {
        var uvI = res.value;
        $(".uvIndex").text("UV Index: " + uvI);
    });

共2个答案

匿名用户

您需要告诉jQuery返回的数据是JSON,可以在ajax函数中提供数据类型:“JSON”,或者使用$.getJSON:

null

var lat = 40;
var lon = 74;

var apiKey1 = "ada1f715672a438e9b9acaa7ea0e930b";
var queryURL2 = `https://api.openweathermap.org/data/2.5/uvi?appid=${apiKey1}&lat=${lat}&lon=${lon}`;

function fetchUV() {
  $.getJSON(queryURL2).then(function(res) {
    var uvI = res.value;
    $(".uvIndex").text("UV Index: " + uvI);
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="fetchUV()">Get UV Index</button>
<p class="uvIndex"></p>

匿名用户

我猜response是这样的对象。

{
  city: {
    coord: {
      lat: "some lat",
      lon: "some lon"
    }
  }
}

如果是这种情况,则您尝试访问latlon的方式是错误的。 应按以下方式访问

var lat = response.city.coord.lat;
var lon = response.city.coord.lon;