在角模仿的getJSON [英] mimicking getJSON in Angular

查看:122
本文介绍了在角模仿的getJSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code,它的工作在角:

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);
    }
  });
},

由于更好的方式通常是使用的$ HTTP,我改变了code这样:

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);
    }
  });
}

现在我收到错误无'访问控制允许来源标头的请求的资源present

Now I receive the error "No 'Access-Control-Allow-Origin' header is present on the requested resource"

但要解决这个错误我用雅虎的代理摆在首位。它让我访问不具有标题中的URL。随着的getJSON一切正常(没有错误,正确的内容),但与$ HTTP我收到错误。有甚至一种方法,使这项工作或做我有.getJSON坚持(并使用$ scope.apply更新变化)

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)

推荐答案

通过添加参数解决了这个回调:JSON_CALLBACK 什么是不是在的getJSON-版本必要

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);
                        }
                    });
            },

这篇关于在角模仿的getJSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆