在 AngularJS 中为 $http 服务使用 JSONP 方法 [英] Using JSONP method for $http service in AngularJS

查看:25
本文介绍了在 AngularJS 中为 $http 服务使用 JSONP 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 AngularJS 的相对新手,并且已经成功地将 $http 的 GET 方法用于基本的概念验证应用程序,我现在正在尝试使用 JSONP 方法从远程 URL 中提取一些 JSON我被给了.我在这里创建了一个基本的 plunker 来展示我想要做什么:http://plnkr.co/edit/Joud0ukAzhgvNM0h9KjB?p=preview

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

我在控制器中使用 HTTP 请求,如下所示:

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

...但我什么也没有得到(除了控制台中的错误").我知道 URL 正在返回有效的 JSON ( http://ec2-54-229-49-250.eu-west-1.compute.amazonaws.com/country?callback=angular.callbacks._0),但我我只是没有得到任何回报...

...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...

推荐答案

JSONP 要求您将您的 JSON 响应包装到 Javascript 函数调用中.当您执行 JSONP 时,请求查询字符串将设置一个名为回调"的参数,该参数将告诉您的服务器如何包装 JSON 响应.

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 会将回调参数定义为 angular.callbacks._0, angular.callbacks._1, angular.callbacks._2 ... 取决于它等待响应的请求数量,因此如果您执行单个请求,响应应该是:

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.

检查您的 Plunker's 网络活动,您将看到该请求正在设置回调参数,但您得到的响应并未包含在其中.

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.

这篇关于在 AngularJS 中为 $http 服务使用 JSONP 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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