问题
I have the following code that works in Angular:
$scope.yqlProxy=function(url, done) {
$.getJSON("http://query.yahooapis.com/v1/public/yql",
{
q: 'select * from json where url="'+url+'"',
format: "json"
},
function(data){
if (data.query.results) {
done(data.query.results);
}
});
},
As the "better" way usually is to use $http I changed the code to this:
$scope.yqlProxy=function(url, done) {
$http.get("http://query.yahooapis.com/v1/public/yql",
{
params: {
q: 'select * from json where url="' + url + '"',
format: "json"
}
})
.success(function(data){
if (data.query.results) {
done(data.query.results);
}
});
}
Now I receive the error "No 'Access-Control-Allow-Origin
' header is present on the requested resource"
But to get around this error I used the yahoo-proxy in the first place. It allowed me to access an url that does not have that header. With getJSON everything is fine (no error, correct content), but with $http I receive that error. Is there even a way to make this work or do I have to stick with .getJSON (and use $scope.apply to update changes)
回答1:
Solved this by adding the parameter "callback: JSON_CALLBACK
" what was not necessary in the getJSON-Version.
So the complete request looks like this:
$scope.yqlProxy=function(url, done) {
$http.jsonp("http://query.yahooapis.com/v1/public/yql",
{
params: {
q: 'select * from json where url="' + url + '"',
format: "json",
callback: "JSON_CALLBACK"
}
})
.success(function(data){
if (data.query.results) {
done(data.query.results);
}
});
},
来源:https://stackoverflow.com/questions/32154809/mimicking-getjson-in-angular