You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

天气应用城市查询API请求400错误排查与解决

天气应用OpenWeatherMap API 400错误排查与解决

我正在开发一款天气应用,用户可通过地理定位或输入城市名称查询天气。使用OpenWeatherMap API时,请求在CodePen上能正常运行,但在VSCode中通过城市输入查询始终返回400错误,最初无法定位问题根源。

原代码

// Get weather from input

function getVal() {
  var val = document.querySelector('#search-city').value;

  const url = 'https://api.openweathermap.org/data/2.5/weather?q=' + val + '&appid={API key}&units=metric';

  $.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    success: (data) => {
      $('#city').text(data.name)
      $('#condition').text(data.weather[0].main);
      $('h1').text(Math.round(data.main.temp));

      backgroundChange(data.weather[0].main);
    },
    error: () => {
      return false
    }
  });
};

// Get weather using location

function geoLocation() {
  if ('geolocation' in navigator) {

    navigator.geolocation.getCurrentPosition((position) => {
      let lat = position.coords.latitude;
      let long = position.coords.longitude;

      let url = 'https://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + long + '&appid={API Key}&units=metric';

      $.ajax({
        url: url,
        type: "GET",
        dataType: 'json',
        success: (data) => {
          $('#city').text(data.name)
          $('#condition').text(data.weather[0].main);
          $('h1').text(Math.round(data.main.temp));

          backgroundChange(data.weather[0].main);
        },
        error: () => {
          return false
        }
      });
    })
  };
});

经排查发现,问题出在getVal函数的定义位置——函数被放在click事件外部,导致API请求在事件触发前就已执行,输入的城市值无法传入请求URL。

修改后的代码

$('.search-icon').click(
function getVal() {

    var city = document.querySelector('#search-city').value;

    const url = 'https://api.openweathermap.org/data/2.5/weather?q='+city+'&appid=dc8c9152e8adaad0ec8bf635818c0d42&units=metric';
      
    $.ajax({
        url: url,
        type: "GET",
        dataType: 'json',
        success: (data) => {
            $('#city').text(data.name)
            $('#condition').text(data.weather[0].main);
            $('h1').text(Math.round(data.main.temp));

            backgroundChange(data.weather[0].main);
        },
        error: () => {
            return false
        }
    });

    
});

将getVal函数嵌套在.search-icon的click事件内后,API请求会在用户点击搜索图标时才执行,能正确获取输入的城市值并传入URL,400错误问题得以解决。

内容的提问来源于stack exchange,提问作者Alex Couture

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 08:48:21