2014-02-13 82 views
-4

問題:問題在於,如果郵政編碼不是有效的,即實際的郵政編碼,頁面就會崩潰。在Javascript函數中處理錯誤

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html> 
<head> 
    <title>VEMap.Geocode Method</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
     <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.3"></script> 
<script type="text/javascript"> 
    var map = null; 

    function GetMap() { 
     map = new VEMap('myMap'); 
     map.LoadMap(); 

    } 

    function ClickGeocode() { 

     map.Geocode(document.getElementById('txtQuery').value, findCallback); 
    } 

    function findCallback(layer, findResults, placeResults, moreResults, error) { 
    var s = ''; 
    if (placeResults) { 
     for (var i = 0; i < placeResults.length; ++i) { 
      s += 'Name: ' + placeResults[i].Name + '\n'; 
      s += 'LatLong: ' + placeResults[i].LatLong + '\n'; 
      s += 'MatchCode: ' + placeResults[i].MatchCode + '\n'; 
      s += 'MatchConfidence: ' + placeResults[i].MatchConfidence + '\n'; 
      s += '\n\n'; 
     } 
    } 
    else { 
     // Code was an error! 
     // Do something else! 
     console.log(error); 
    } 

    } 
</script> 


+4

好的,你怎麼知道它是無效的? –

+1

你能提供jsFiddle demo –

+0

如果你改變郵編來說「12345XYZ」,它會引發錯誤。 @MattBurland – indofraiser

回答

1

看着你的代碼和清理你的fiddle它看起來像您可以只需檢查placeResults是否爲空:

function findCallback(layer, findResults, placeResults, moreResults, error) { 
     var s = ''; 
     if (placeResults) { 
      for (var i = 0; i < placeResults.length; ++i) { 
       s += 'Name: ' + placeResults[i].Name + '\n'; 
       s += 'LatLong: ' + placeResults[i].LatLong + '\n'; 
       s += 'MatchCode: ' + placeResults[i].MatchCode + '\n'; 
       s += 'MatchConfidence: ' + placeResults[i].MatchConfidence + '\n'; 
       s += '\n\n'; 
      } 
     } 
     else { 
      // Code was an error! 
      // Do something else! 
      console.log(error); 
     } 
    } 
+0

謝謝,也添加到主代碼中 – indofraiser

1

如果txtQuery持有的郵政編碼,那麼試試這個:

var defaultPostalCode = 'xy12345'; 

function ClickGeocode() { 
    var postalCode = document.getElementById('txtQuery').value; 
    if (!isValidPostalCode(postalCode, 'US')) { 
     postalCode = defaultPostalCode; 
    } 
    map.Geocode(postalCode, findCallback); 
} 

function isValidPostalCode(postalCode, countryCode) { 
    switch (countryCode) { 
     case "US": 
      postalCodeRegex = /^([0-9]{5})(?:[-\s]*([0-9]{4}))?$/; 
      break; 
     case "CA": 
      postalCodeRegex = /^([A-Z][0-9][A-Z])\s*([0-9][A-Z][0-9])$/; 
      break; 
     default: 
      postalCodeRegex = /^(?:[A-Z0-9]+([- ]?[A-Z0-9]+)*)?$/; 
    } 
    return postalCodeRegex.test(postalCode); 
} 
+1

我想我需要更好地說我的查詢@DennisT我的意思是,如果他們的郵編沒有找到,而不是正確的結構。因此,讓我們說「AA1 1AA」是一個有效的英國郵政編碼,但我輸入「AA1 2AA」,但不存在。我想處理該問題,理想情況下將錯誤消息放在標籤中,但是沒有任何操作也起作用,例如,儘量捕獲.Net – indofraiser