jquery .ajax() method fail
Can anyone tell me what might be wrong with this javascript?
$.ajax({
cache:false,
url: 'http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false',
success: function(data, textStatus, jqXHR) {
console.log('success');
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.lo开发者_运维百科g('error');
console.log(errorThrown);
console.log(jqXHR);
}
});
The 'error' event handler function is invoked and this is my console output:
error
undefined
XMLHttpRequest { mozResponseArrayBuffer=ArrayBuffer, status=0, more...}
I'm trying to learn how to make ajax calls with jquery, and I'm still pretty new to it.
I think you're doing a Cross domain request, which is blocked by your browser.
You could directly use the Maps API, which has convenient methods for such things.
Maps Documentation
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
I've just run this block of code through JSFiddle and get the same error problem.
however, when I go directly to the request URL I get this block of JSON:
{
"status": "REQUEST_DENIED",
"results": [ ]
}
Are you getting the same ?
The first problem is that you can't make cross-domain Ajax requests without some extra work - you must use JSONP and not just 'plain' JSON or the server must allow the CDR via the appropriate access-control headers[ref].
However, the bigger problem here is that with v3 of the API, Google has taken away the ability to make JSONP requests (or at least it is undocumented at the moment). They would prefer you to use the Google Maps library geocoder instead:
var geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'address': '1600+Amphitheatre+Parkway,+Mountain+View' }, function(data, status){ console.log(data); //data is an array of results });
For the moment, you could fall back to the v2 API if you absolutely must have Ajax geocoding but don't want to use the geocoder built into the Google Maps JS library:
$.ajax({
cache: false,
url: 'http://maps.google.com/maps/geo?q=1600+Amphitheatre+Parkway,+Mountain+View,+CA&output=json&sensor=false&key=<your_key_here>',
success: function(data, textStatus, jqXHR) {
console.log('success');
console.log(data); //geocoded data
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
console.log(jqXHR);
},
jsonp: 'callback',
dataType: 'json'
});
精彩评论