首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过角从Firebase主机获取JSONP文件

通过角从Firebase主机获取JSONP文件
EN

Stack Overflow用户
提问于 2014-08-29 08:12:20
回答 1查看 610关注 0票数 1

我正在尝试从远程防火墙服务器获取一个.json文件。

代码语言:javascript
复制
function fetchData(remoteJsonId){
    var url = "https://myAppName.firebaseapp.com/topics/"+remoteJsonID;
    console.log(url); //This variable expands to the full domain name which is valid and                       returns success both on wget and the browser
    $http.jsonp(url).then(
        function(resp){

        },
        function(err){
            console.log(err.status) // This posts "404" on console.
        }
    );
}

但是,如果我在浏览器中打开url,json文件将加载。即使我wget url加载json文件。但通过角度,它返回一个404未找到。

现在,.json远程文件具有以下结构:

代码语言:javascript
复制
[
  { 
    "hello":"Europe"
  },

  {
    "hello":"USA"
  }
]

可以使用$http.get()获取上述文件,但不能使用$http.jsonp()。JSONP不能用上述结构解析.json文件。我怎么才能解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-29 15:26:52

您需要在传递给?callback=JSON_CALLBACK的URL中指定一个$http.jsonp

来自 documentation

代码语言:javascript
复制
jsonp(url, [config]);
Shortcut method to perform JSONP request.

Parameters
Param   Type    Details
url     string  
Relative or absolute URL specifying the destination of the request.
The name of the callback should be the string JSON_CALLBACK.

最后一行是你错过的。

一个简单的示例(使用Firebase数据库,而不是Firebase宿主):

代码语言:javascript
复制
var app = angular.module('myapp', []);
app.controller('mycontroller', function($scope, $http) {
  var url = 'https://yourfirebase.firebaseio.com/25564200.json';
  $http.jsonp(url+'?callback=JSON_CALLBACK').then(
    function(resp){
      console.log(resp.data); // your object is in resp.data
    },
    function(err){
        console.error(err.status)
    }
  );  
});

如果你想看到它起作用:http://jsbin.com/robono/1/watch?js,console

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25564200

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档