[英]Loading JSON cross-domain using an HTTPS url with AngularJS
我正在尝试使用以下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文件。 如果我尝试使用其他URL,即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文件?
对于跨域,您必须使用CORS,请在此处查看CORS上的这篇文章,如果需要可以使用jsonp,但是您不能使用jsonp进行发布。希望它会有所帮助
起作用的是以下内容:
将$http.get
替换$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.
});
;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.