加载使用JSON与AngularJS
问题描述:
我尝试使用下面的AngularJS代码从一个URL一些JSON数据的HTTPS URL跨域:加载使用JSON与AngularJS
'use strict';
/* Controllers */
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', function($scope, $http) {
$scope.test = "Not loaded";
delete $http.defaults.headers.common['X-Requested-With'];
$http.get('https://live.mpare.net/users.json').success(function(data) {
$scope.test = data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
;
});
然而,JSON文件不装载。如果我尝试不同的网址,即http://ip.jsontest.com,那么确实是的工作。
我检索使用curl的HTTPS网站标题:
HTTP/1.1 200 OK
Date: Sat, 08 Nov 2014 10:53:04 GMT
Server: Apache/2.2.29 (Amazon)
X-Powered-By: PHP/5.3.29
Set-Cookie: PHPSESSID=epp00ffbe0nmtogpj8dcvnfvg2; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 119
Connection: close
Content-Type: application/json
为HTTP网站的标题是这样的:
HTTP/1.1 200 OK
Date: Sat, 08 Nov 2014 10:53:04 GMT
Server: Apache/2.2.29 (Amazon)
X-Powered-By: PHP/5.3.29
Set-Cookie: PHPSESSID=epp00ffbe0nmtogpj8dcvnfvg2; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 119
Connection: close
Content-Type: application/json
我如何可以加载HTTPS JSON文件?
答
什么工作是如下:
将$http.get
替换为$http.jsonp
并将?callback=JSON_CALLBACK
放在url的末尾。以下代码适用于我:
'use strict';
/* Controllers */
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', function($scope, $http) {
$scope.test = "Not loaded";
delete $http.defaults.headers.common['X-Requested-With'];
$http.jsonp('https://live.mpare.net/users.json?callback=JSON_CALLBACK').success(function(data) {
$scope.test = data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
;
});
没有CORS。 – dfsq 2014-11-08 11:16:48