我是AngularJS的相对新手,并成功使用$ http的GET方法作为基本的概念验证应用程序,我现在正尝试使用JSONP方法从远程URL中提取一些JSON我是得到了.我在这里创建了一个基本的plunker来展示我想要做的事情:http://plnkr.co/edit/Joud0ukAzhgvNM0h9KjB?p = preview
我在我的控制器中使用HTTP请求,如下所示:
$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');
});
Run Code Online (Sandbox Code Playgroud)
...但是我什么都没有回来(除了控制台中的"错误").我知道URL返回有效的JSON(http://ec2-54-229-49-250.eu-west-1.compute.amazonaws.com/country?callback=angular.callbacks._0),但我是只是没有得到任何回报......
Ber*_*and 10
JSONP要求您将JSON响应包装到Javascript函数调用中.当您执行JSONP时,请求查询字符串将设置一个名为"callback"的参数,该参数将告诉您的服务器如何包装JSON响应.
所以响应应该是这样的:
callback([
{"id": "1", "name": "John Doe"},
{"id": "2", "name": "Lorem ipsum"},
{"id": "3", "name": "Lorem ipsum"}
]);
Run Code Online (Sandbox Code Playgroud)
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"}
]);
Run Code Online (Sandbox Code Playgroud)
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.

| 归档时间: |
|
| 查看次数: |
15036 次 |
| 最近记录: |