如何使用jQuery AJAX处理API调用错误?

时间:2022-04-13 08:57:05

I am making a weather app as a school project. I have an input through which the user is supposed to enter a name of a city to get the weather from an API. If the user misspells the name of the city I get an error in the console. I'd like to catch this when it happens and display some message to inform the user to correct the input. I searched other questions on * and jQuery site as well, but didn't get my answer so that's why I'm here.

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

My code looks like this:

我的代码如下所示:

$.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}

I tried putting the ajax inside a try/catch block and added error: function().. beneath success, it still doesn't display an error message.

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

Why isn't this working? Is this easier to do in plain javascript?

为什么这不起作用?这在普通的javascript中更容易吗?

2 个解决方案

#1


1  

Add an if statement to your success function to check if the list has elements in it. Otherwise you will get an error trying to get the name of an element that doesn't exist.

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

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

#2


-2  

From your comment it seems that you go and use this:

从你的评论看来你似乎去使用这个:

weatherData.list[0].name

your response as you mentioned is like this

你提到的回答是这样的

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

You should check your response in order to see if you have any server errors.

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

My guess from what you have provided seems like you don't take into consideration neither the response code nor the number of items. You should change your ajax success handler to something like the following.

我对您提供的内容的猜测似乎没有考虑到响应代码和项目数量。您应该将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)));
        }  
    }

});

#1


1  

Add an if statement to your success function to check if the list has elements in it. Otherwise you will get an error trying to get the name of an element that doesn't exist.

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

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

#2


-2  

From your comment it seems that you go and use this:

从你的评论看来你似乎去使用这个:

weatherData.list[0].name

your response as you mentioned is like this

你提到的回答是这样的

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

You should check your response in order to see if you have any server errors.

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

My guess from what you have provided seems like you don't take into consideration neither the response code nor the number of items. You should change your ajax success handler to something like the following.

我对您提供的内容的猜测似乎没有考虑到响应代码和项目数量。您应该将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)));
        }  
    }

});