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

使用jQuery AJAX调用OpenWeatherMap API时持续出现404错误求助

问题排查与解决

核心问题:URL缺少协议前缀

请求返回404的直接原因是URL未添加https://(或http://)协议前缀。当你直接写api.openweathermap.org/...时,浏览器会将其识别为当前页面的相对路径(比如本地打开的file:///xxx/index.html页面,浏览器会错误请求file:///xxx/api.openweathermap.org/...),该路径不存在,因此返回404。

修改后的代码

给URL补上https://前缀即可修复:

$(document).ready(function() {
  $(".search button").click(function() {
    getWeather($(".search-bar").val());
  });
});

function getWeather(city) {
  var metric = "&units=metric";
  var myAPI = "4f41b20d31ef924373402ebf9b9fe310";
  // 补充https://协议前缀
  var url = "https://api.openweathermap.org/data/2.5/forecast?q=" + city + metric + "&appid=" + myAPI;

  $.getJSON(url, function(data) {
    console.log(data);
  })
}

额外注意事项

  • API密钥安全:你直接公开了OpenWeatherMap的API密钥,建议立即更换密钥,防止被他人滥用导致服务额度耗尽。
  • 跨域限制:如果修复URL后出现跨域错误,需确认OpenWeatherMap API是否支持前端直接调用,若不支持,可通过后端代理请求绕过浏览器的跨域限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:42:42