2010-10-17 175 views
2

谁能帮我明白为什么下面的代码不会显示在第二个提醒的任何内容?浏览到我传递给的getJSON()相同的URL在浏览器窗口中产生输出。jQuery的谷歌地图质疑

<!DOCTYPE html> 
<html> 
<head> 
    <script src="http://code.jquery.com/jquery-latest.min.js"></script> 
</head> 
<body> 
    <script> 
     $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address=Chicago,IL&sensor=false', 
      function(json, textStatus) { 
       alert("textStatus:" + textStatus); 
       var out = ''; 
       for (var i in json) { 
        out += i + ": " + json[i] + "\n"; 
       } 
       alert(out); 
       //alert("JSON Data:" + json.results[0].formatted_address); 
      }); 
    </script> 
</body> 
</html> 

回答

1

问题与same origin policy有关。 This post非常有帮助。我修改了我的代码以使用Client-side Google Maps Geocoding API。这里是工作代码:

<!DOCTYPE html> 
<html> 
<head> 
    <script src="http://code.jquery.com/jquery-latest.min.js"></script> 
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
    <script type="text/javascript"> 
     var geocoder; 
     $(document).ready(function() { 
      geocoder = new google.maps.Geocoder(); 
     }); 
     function codeAddress() { 
      var address=$('#address').val(); 
      geocoder.geocode({ 'address': address}, function(results, status) { 
       if (status == google.maps.GeocoderStatus.OK) { 
        $('#location').html('<p><b>Location:</b>' + results[0].geometry.location + '</p>'); 
       } else { 
        alert("Geocode was not successful for the following reason: " + status); 
       } 
      }); 
     } 
    </script> 
</head> 
<body> 
    <div> 
     <input id="address" type="textbox" value="Chicago,IL"/> 
     <input type="button" value="Geocode" onclick="codeAddress()" /> 
    </div> 
    <div id="location"> 
    </div> 
</body> 
</html> 
0

看来你 OBJ变量是不确定的。您的意思是:

out += i + ": " + json[i] + "\n"; 
+0

Doh!好决定。我在原来的帖子中解决了这个问题,但第二个提醒仍然没有任何内容。 – nhavens 2010-10-17 20:11:43

+0

尝试在for循环中添加警报。那么,第一次突破之后,否则你会被解雇的对话在接下来的几个小时... – TuomasR 2010-10-17 20:29:46

+0

我试图移动警报(出)里面的for循环,但后来我停下来获得第二警报。 – nhavens 2010-10-18 19:38:53