2011-05-06 52 views
0

我有一个自动完成的输入,访问者输入一个位置,并提供建议,而你键入。我为此使用了Geonames Web服务器。jquery错误函数返回异常消息

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

返回的异常消息是JSON。

这是带有error()函数的脚本的一部分。我故意在数据中的用户名参数中输入错误以获得错误,但不会显示警报。

$(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!"); 
         })); 
        },            
       });    
      }, 
+0

你不能从async-called-functions中返回数据。 – 2011-05-06 22:48:48

回答

1

国地名将在成功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){ 
     ... 

} 

希望这有助于。欢呼声

+0

谢谢!代码完美无缺! – CyberJunkie 2011-05-07 01:06:44

1

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

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

谢谢您的注意!我做了一个非常新手的错误:( – CyberJunkie 2011-05-07 01:07:14