无法从天气API获取数据,输入城市名触发400 Bad Request错误(JS)
Let’s break down exactly why you’re hitting that 400 error and how to fix it step by step:
Primary Issue: Unencoded City Name Input
The most common trigger for this 400 error is unhandled special characters (like spaces) in your city name input. For example, if you type "New York", your URL becomesq=New York—spaces aren’t valid in URLs, so the API rejects the request immediately. Fix this by wrapping your city name withencodeURIComponent()to properly encode any non-URL-safe characters:const cityName = encodeURIComponent($("#city").val());This will convert spaces to
%20and other special characters to their URL-friendly equivalents, ensuring the API can parse your request correctly.Secondary Issue: Incorrect Response Property Access
Even if you fix the request, your current code will fail to render data because you’re accessing the wrong properties in the API response:- Temperature values (
temp,feels_like) live inside themainobject, not directly on the rootdataobject weatheris an array of weather objects—you’ll need to grab a specific property from the first item (likemainordescription)
Here’s the corrected
.then()block to fix rendering:.then( (data) => { console.log(data); $("#name").text(data.name); $("#temp").text(data.main.temp); $("#feels").text(data.main.feels_like); $("#weather").text(data.weather[0].main); }, (error) => { console.log("bad request: ", error); })- Temperature values (
Bonus: Add Input Validation
To avoid empty requests (which also throw 400 errors), add a quick check before making the API call:function handleGetData(event){ event.preventDefault(); const cityName = encodeURIComponent($("#city").val().trim()); // Block empty submissions if (!cityName) { alert("Please enter a valid city name!"); return; } // Rest of your AJAX code... }
Full Corrected Code
function handleGetData(event){ event.preventDefault(); const cityName = encodeURIComponent($("#city").val().trim()); if (!cityName) { alert("Please enter a valid city name!"); return; } $.ajax({ url: `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&units=imperial&appid=99df413c60279878184277e08a2c6863` }) .then( (data) => { console.log(data); $("#name").text(data.name); $("#temp").text(data.main.temp); $("#feels").text(data.main.feels_like); $("#weather").text(data.weather[0].main); }, (error) => { console.log("bad request: ", error); }); console.log("It's working!"); } $('form').on("submit", handleGetData);
内容的提问来源于stack exchange,提问作者Deannaleenormanmsncom

