2014-11-08 60 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. 
    }); 
    ; 
});