Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

javascript - Obtaining JSONP files from Firebase hosting through Angular

I am trying to obtain a .json file from remote firebase server.

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

But If I open url in the browser the json file loads. Even if I wget url the json file loads. But through angular it returns a 404 not found.

Now the .json remote file has this structure:

[
  { 
    "hello":"Europe"
  },

  {
    "hello":"USA"
  }
]

The above file can be fetched using $http.get() but not with $http.jsonp(). JSONP cant parse .json file with the above structure. How can I work around this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to specify a ?callback=JSON_CALLBACK in the URL that you pass to $http.jsonp.

From Angular's $http.jsonp documentation:

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.

That last line is what you're missing.

A simple example (using a Firebase database, not Firebase hosting):

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

In case you want to see it working: http://jsbin.com/robono/1/watch?js,console


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...