2011-05-06 41 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