如何用jQueryAJAX处理API调用错误



我正在制作一个天气应用程序作为学校项目。我有一个输入,用户应该通过它输入一个城市的名称,从API获得天气。如果用户拼错了城市的名称,我会在控制台中得到一个错误。我想在发生这种情况时捕捉到它,并显示一些消息来通知用户更正输入。我也在StackOverflow和jQuery网站上搜索了其他问题,但没有得到答案,所以这就是我来这里的原因。

我的代码如下:

$.ajax({
type: 'GET',
url: 'http://api.openweathermap.org/data/2.5/find?q=' + valueFromInput + '&units=metric&type=like&mode=json&APPID=cdb7ecf86aa724f19f723f964e5f15ae',
dataType: 'json',
success: function (weatherData) {...//code}

我尝试将ajax放入try/catch块中,并添加了错误:function((。。在成功的背后,它仍然不会显示错误消息。

为什么不起作用?这在纯javascript中更容易做到吗?

在成功函数中添加if语句,以检查列表中是否包含元素。否则,在尝试获取不存在的元素的名称时会出错。

success: function (weatherData) {
if (weatherData.list.length > 0)  
document.getElementById("cityNameCountry_").appendChild(document.createTextNode((weatherData.list[0].name)));
}

从您的评论来看,您似乎使用了以下内容:

weatherData.list[0].name

你提到的回复是这样的

"message":"like","cod":"200","count":0,"list":[]

您应该检查您的响应,以查看是否有任何服务器错误。

根据您提供的信息,我猜您似乎既没有考虑响应代码,也没有考虑项目数量。您应该将ajax成功处理程序更改为以下内容。

$.ajax({
type: 'GET',
url: 'http://api.openweathermap.org/data/2.5/find?q=' + valueFromInput + '&units=metric&type=like&mode=json&APPID=cdb7ecf86aa724f19f723f964e5f15ae',
dataType: 'json',
success: function (result) {
// Error handling
if (result.code != '200'){
alert('some kind of error');
return false;
}
// Checking the number of list items
if (result.list.length > 0){
document.getElementById("cityNameCountry_").appendChild(document.createTextNode((result.list[0].name)));
}  
}
});

最新更新