3

I'm a relative newbie to AngularJS, and having successfully used the GET method of $http for a basic proof-of-concept app, I'm now trying to use the JSONP method to pull some JSON from a remote URL I've been given. I've created a basic plunker here to show what I'm trying to do: http://plnkr.co/edit/Joud0ukAzhgvNM0h9KjB?p=preview

I'm using an HTTP request inside my controller like this:

    $http({method: 'jsonp', url: 'http://ec2-54-229-49-250.eu-west-1.compute.amazonaws.com/country?callback=JSON_CALLBACK'}).
  success(function(data) {
    $scope.countries = data;
    console.log('success');
  }).
  error(function(data) {
    console.log('error');
  });    

...but I'm getting nothing back at all (except 'error' in the console). I know the URL is returning valid JSON ( http://ec2-54-229-49-250.eu-west-1.compute.amazonaws.com/country?callback=angular.callbacks._0 ), but I'm just not getting anything back...

4

1 回答 1

10

JSONP requires you to wrap your JSON response into a Javascript function call. When you do a JSONP the request query string will set a parameter called 'callback' that will tell your server how to wrap the JSON response.

So the response should be something like:

callback([
    {"id": "1", "name": "John Doe"},
    {"id": "2", "name": "Lorem ipsum"},
    {"id": "3", "name": "Lorem ipsum"}
]);

Angular will define the callback parameter as angular.callbacks._0, angular.callbacks._1, angular.callbacks._2 … depending on how many requests it is waiting for response, so if you do a single request the response should be:

angular.callbacks._0([
    {"id": "1", "name": "Lorem ipsum"},
    {"id": "2", "name": "Lorem ipsum"},
    {"id": "3", "name": "Lorem ipsum"}
]);

The server should use the callback parameter from the request string to set the response accordingly.

Check your Plunker's network activity and you will see that the request is setting the callback parameter but the response you are getting is not being wrapped with it.

enter image description here

于 2013-06-12T10:41:44.310 回答