我尝试使用以下AngularJS代码从URL获取一些JSON数据:
'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文件?
答案 0 :(得分:1)
对于跨域你必须使用CORS,查看CORS here上的这篇文章,你可以使用jsonp,但是你不能用它来发帖。希望它有帮助
答案 1 :(得分:-1)
以下是有效的:
将$http.get
替换为$http.jsonp
,并将?callback=JSON_CALLBACK
放在网址的末尾。以下代码对我有用:
'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.
});
;
});