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

天气应用中输入错误城市名时添加Alert提示的最简实现方法

最简添加Alert错误提示的方法

要给这个天气应用添加错误提示,只需做两处关键修改,覆盖输入无效数字/空值和城市名拼写错误两种场景:

1. 前端输入合法性校验

在search方法里先对用户输入做基础判断,避免无效请求:

search: function() {
  const inputVal = document.querySelector(".search_bar").value.trim();
  // 过滤空输入或纯数字输入
  if (!inputVal || /^\d+$/.test(inputVal)) {
    alert("请输入有效的城市名称");
    return;
  }
  this.fetchWeather(inputVal);
}

2. API返回错误处理

OpenWeatherMap API在城市不存在时会返回cod: "404"(非200的状态码),在fetchWeather里添加错误判断:

fetchWeather: function(city) {
  fetch(
      "https://api.openweathermap.org/data/2.5/weather?q=" +
      city + "&units=metric&appid=fa73f7986fd7a4a71b32273d81cd9fce"
    )
    .then((response) => response.json())
    .then((data) => {
      // 检查API请求是否成功
      if (data.cod !== 200) {
        alert("未找到该城市,请检查拼写是否正确");
        return;
      }
      this.displayWeather(data);
    });
}

修改后的完整代码

let weather = {
  fetchWeather: function(city) {
    fetch(
        "https://api.openweathermap.org/data/2.5/weather?q=" +
        city + "&units=metric&appid=fa73f7986fd7a4a71b32273d81cd9fce"
      )
      .then((response) => response.json())
      .then((data) => {
        if (data.cod !== 200) {
          alert("未找到该城市,请检查拼写是否正确");
          return;
        }
        this.displayWeather(data);
      });
  },
  displayWeather: function(data) {
    const { name } = data;
    const { icon , description } = data.weather[0];
    const { temp , humidity } = data.main;
    const { speed } = data.wind;

    document.querySelector(".city").innerHTML = "Weather in " + name;
    document.querySelector(".icon").src = "https://openweathermap.org/img/wn/" + icon + ".png";
    document.querySelector(".description").innerHTML = description;
    document.querySelector(".temp").innerHTML = temp + " °C";
    document.querySelector(".humidity").innerHTML = "Humidity : " + humidity + " %";
    document.querySelector(".wind").innerHTML = "Wind Speed : " + speed + " km/h";
  },

  search: function() {
    const inputVal = document.querySelector(".search_bar").value.trim();
    if (!inputVal || /^\d+$/.test(inputVal)) {
      alert("请输入有效的城市名称");
      return;
    }
    this.fetchWeather(inputVal);
  }
}

document.querySelector(".search").addEventListener("click", function() {
  weather.search();
})

说明

  • 前端校验:提前拦截空输入、纯数字输入,减少无效API请求的同时即时提示用户
  • API错误处理:通过返回数据的cod字段判断请求结果,捕获城市不存在的错误并提示用户

内容的提问来源于stack exchange,提问作者Law Lite

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 01:15:51