任何人都可以帮助我理解为什么以下代码不会在第二个警报中显示任何内容?浏览到我传递给getJSON()的同一个url会在浏览器窗口中生成输出。
<!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>
答案 0 :(得分: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>
答案 1 :(得分:0)
您的 obj 变量似乎未定义。你的意思是:
out += i + ": " + json[i] + "\n";