mimicking getJSON in Angular

落爺英雄遲暮 提交于 2019-12-24 16:04:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!