我希望当用户输入无效的城市名称时弹出警报。
已尝试使用if-else和try-catch方法,但不起作用。我正在使用Weather API来获取天气和温度。
const getWeather = () => {
let cityName = $("#cityName").val();
let apiCall = `http://api.openweathermap.org/data/2.5/weather?q=${cityName}&mode=json&units=metric&appid=${
CONSTANTS.appId
}`;
$.getJSON(apiCall, weatherData => {
let cityName = weatherData.name;
let countryName = weatherData.sys.country;
let description = weatherData.weather[0].description;
let tempMin = weatherData.main.temp_min;
let tempMax = weatherData.main.temp_max;
$("#city").text(cityName);
$("#detail").text(description);
$("#country").text(countryName);
$("#mintemp").html(`Minimum: ${tempMin}<span>℃</span>`);
$("#maxtemp").html(`Maximum: ${tempMax}<span>℃</span>`);
});
};
每当输入无效的输入时,我都会在控制台中收到此消息。
GET http://api.openweathermap.org/data/2.5/weather?q=sdx&mode=json&units=metric&appid=d568dc579415266146ede4b4f9de029b 404 (Not Found)
jquery-3.4.1.js:9837
我不希望出现错误,而是使用错误来显示一条消息,说明无效的用户输入。
发布于 2019-05-24 16:25:10
在这种情况下,您不需要try...catch
块,因为jQuery会为您处理所有事情,但您需要嗅探HTTP Status Code。不要使用$.getJSON()
,而要使用$.ajax()
。
如果您仍然想使用$.getJSON()
,可以通过以下方式使用.fail()
链接方法:
let cityName = $("#cityName").val();
let apiCall = `http://api.openweathermap.org/data/2.5/weather?q=${cityName}&mode=json&units=metric&appid=${CONSTANTS.appId}`;
$.getJSON(apiCall, weatherData => {
let cityName = weatherData.name;
let countryName = weatherData.sys.country;
let description = weatherData.weather[0].description;
let tempMin = weatherData.main.temp_min;
let tempMax = weatherData.main.temp_max;
$("#city").text(cityName);
$("#detail").text(description);
$("#country").text(countryName);
$("#mintemp").html(`Minimum: ${tempMin}<span>℃</span>`);
$("#maxtemp").html(`Maximum: ${tempMax}<span>℃</span>`);
}).fail(() => {
alert("City doesn't Exist!!");
$("#cityName").val("");
$("#city").text("");
$("#detail").text("");
$("#country").text("");
$("#mintemp").html("");
$("#maxtemp").html("");
});
https://stackoverflow.com/questions/56288482
复制相似问题