2014-11-08 57 views
0

我尝试使用下面的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文件?

+0

没有CORS。 – dfsq 2014-11-08 11:16:48

回答

1

你必须使用CORS,检查CORS here本文跨域,您可以使用JSONP如果你想,但你不能这样做后调用与that.Hope它有助于

+0

谢谢,这让我走上正轨! – Jetze 2014-11-08 11:40:55

0

什么工作是如下:

$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. 
    }); 
    ; 
});