[英]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.