问题
I'm using jQuery to access Yahoo's Geolocation APIs. Even though I am able to successfully retrieve data from their servers, I cannot get jQuery to successfully parse the data. I've tried both $.ajax() and $.getJSON, each returns the same failures: parsererror and "invalid label".
Through my digging on the interwebs, I've discovered that "invalid label" is likely the result of the JSON not being wrapped in parentheses, but I can't figure out how to wrap the data up, prior to it getting parsed. I'm not even convinced that's the problem.
Here's my code:
$(document).ready(function() {
var url = "http://where.yahooapis.com/geocode?q=39.0334171,-94.8320452&gflags=R&flags=JT&appid=supersecretappid&callback=?";
$.getJSON(url, function() { alert("success"); })
.error(function(data) { alert(JSON.stringify(data)); });
});
The alternate version using just $.ajax is as follows:
$.ajax({
url: url,
data: {},
dataType: "jsonp",
contentType: "text/plain",
success: function(json) {
alert("success");
},
error: function(x,y,z) {
alert(JSON.stringify(x));
}
});
Much thanks in advance.
回答1:
The API you are trying to access doesn't support JSONP. So you cannot use it with javascript due to same origin policy restrictions. Try pasting the following url in your browser:
http://where.yahooapis.com/geocode?q=39.0334171,-94.8320452&gflags=R&flags=JT&appid=supersecretappid&callback=foo
See how the callback
parameter is completely ignored? The server returns pure JSON, not JSONP which is what you need. As a workaround you could write a server side script on your domain that will act as a bridge between Yahoo and your domain. Then you will send the AJAX request to your script.
来源:https://stackoverflow.com/questions/6803800/invalid-label-parsererror-with-jquery-and-yahoos-geolocation-apis