您可以尝试以下完善代码:

<div id="weather-widget">
  <h3>天气</h3>
  <div id="weather-data">正在加载天气信息...</div>
</div>

<script>
  // 根据IP获取地理位置坐标
  function getCoordinatesByIP() {
    return fetch('http://ip-api.com/json')
      .then(response => response.json())
      .then(data => {
        const lat = data.lat;
        const lon = data.lon;
        return { latitude: lat, longitude: lon };
      });
  }

  // 根据经度和纬度坐标获取天气信息
  function getWeatherData(coordinates) {
    const { latitude, longitude } = coordinates;
    const url = `https://devapi.qweather.com/v7/weather/now?location=${latitude},${longitude}&key=f774e589423646f889db7c4061d89d74`;
    return fetch(url)
      .then(response => response.json())
      .then(data => data.now);
  }

  // 更新天气信息
  function updateWeatherInfo(weather) {
    const weatherDataElement = document.getElementById("weather-data");
    weatherDataElement.innerHTML = `
      天气:${weather.text}<br>
      温度:${weather.temp}°
    `;
  }

  // 执行获取天气信息的操作
  getCoordinatesByIP()
    .then(coordinates => getWeatherData(coordinates))
    .then(weather => updateWeatherInfo(weather))
    .catch(error => console.log(error));
</script>

这段代码首先定义了两个函数,getCoordinatesByIPgetWeatherData,用于获取地理位置坐标和天气信息。然后定义了updateWeatherInfo函数,用于更新天气信息的显示。

最后,在执行过程中,我们首先调用getCoordinatesByIP获取地理位置坐标,然后将坐标传递给getWeatherData获取天气信息,并将获取到的天气信息传递给updateWeatherInfo更新天气信息的显示。

请注意,由于涉及到跨域请求,您需要在真实服务器环境下运行该代码,或者使用支持跨域请求的开发工具进行测试

div id=weather-widget h3天气h3 div id=weather-data 正在加载天气信息 div div script 根据IP获取地理位置坐标 function getCoordinatesByIP return fetchhttpip-apicomjson thenresponse = responsejson thendata = const ip = dat

原文地址: https://www.cveoy.top/t/topic/iND1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录