该表单被设置为将用户输入收集到地址变量中。使用 jQuery 序列化每个 url 要求的地址。jquery serialize 使用 getJSON 将请求发送到 google geocode api。在 for 循环中使用 for in 循环来运行结果。最后,访问 JSON 结果。
问题:为什么我会得到undefined
这样的结果?
代码:
$(function() {
var address = document.getElementById('address').value;
address += " "+document.getElementById('street_add').value;
address += " "+document.getElementById('city').value;
address += " "+document.getElementById('state').value;
address += " "+document.getElementById('postcode').value;
$('#clickme').click(function() {
var strAddress = $( "address" ).serialize();
// data is an object containing info also called a map key/values
$.getJSON("http://maps.googleapis.com/maps/api/geocode/json?address=strAddress&sensor=false", function( data ) {
for (var i = 0; i <= data.length; i++) {
for (key in data.results[i]) {
var mystring = data.results[0].formatted_address;
var mylat = data.results[0].geometry.location.lat;
var mylng = data.results[0].geometry.location.lng;
}
}
$("<ul/>", {
"class": "zombies",
html: document.write(mystring,'<hr />', mylat, '<hr />', mylng),
}).appendTo( "body" );
});
});
});