Jquery错误函数返回异常消息

时间:2011-05-06 22:44:27

标签: jquery json api map geonames

我有一个自动完成输入,访问者输入一个位置,并在您输入时提供建议。我正在使用Geonames Web服务器。

如果Geonames Web服务器上发生错误,我正在尝试返回异常消息。例如,如果我超出了我的Web服务器请求限制,我希望脚本向我发送电子邮件警报。

返回的异常消息是JSON。

这是带有error()函数的脚本的一部分。我故意在数据中的username参数中输入错误以获取错误但不显示警告。

$(function() {
        $( "#city" ).autocomplete({
            source: function( request, response ) {
                $.ajax({
                    url: "http://api.geonames.org/searchJSON",
                    dataType: "jsonp",
                    data: {
                        q: request.term,
                        countryBias: "US",
                        featureClass: "P",
                        style: "full",
                        maxRows: 10,
                        ussername: "demo",
                        operator: "OR"
                    },
                    success: function( data ) {
                        response( $.map( data.geonames, function( item ) {                                                           
                            return {
                                label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                                value: item.name,
                                saved_country: item.countryName,
                                saved_state: item.adminName1,
                                saved_city: item.name,
                                saved_zipcode: item.postalcode,
                                saved_latitude: item.lat,
                                saved_longitude: item.lng,                                                                                              
                            }
                        }));  
                    },  
                    error: function( data ) {
                        response( $.map( data.geonames, function( item ) {                                                           
                            return {
                                request_status: item.status                             
                            }
                            alert("Error msg!");
                        }));  
                    },                                              
                });             
            },

2 个答案:

答案 0 :(得分:1)

项尚未在该范围内声明。试试这个:

error: function( data ) {  
    var request_status= data.status;  
    //do stuff with status  
}

答案 1 :(得分:1)

Geonames将在success hundler中返回此错误信息,而不是错误处理程序。因此,您必须在成功函数内部询问:

success: function( data ) {
    if(typeof(data.status) != 'undefined'){ //It means there was an error
       var errorObject = data;
       //Now you have access to errorObject.status, errorObject.status.message and so on
       //Do something with your error object
       return; //Avoid execution of the rest of the code of this function
    } //Can add an else here if you want
    response( $.map( data.geonames, function(item){
      ...

}

希望这会有所帮助。干杯