2015-11-17 54 views
14

我想從本地機器上的JSON文件中獲取數據。但我無法獲取數據。它顯示$ http的一些跨域錯誤。在angularjs中從本地JSON文件中獲取數據

這是我的代碼。

angular.module('myApp',[]).controller('myCtrl', function ($scope, webtest) {webtest.fetch().then(function (data) {$scope.accounttype = data;})}); .factory('webtest', function($q, $timeout, $http) {var Webtest = { 
    fetch: function(callback) { 
     return $timeout(function() { 
      return $http.get('webtest.json').then(function(response) { 
       return response.data; 
      }); 
     }, 30); 
    } 
}; 
return Webtest;}); 

任何人都請幫助我如何顯示來自本地JSON文件的數據? 在此先感謝。

+0

你能不能加一個小提琴] – Shreyas

+0

你能不能告訴我們具體的錯誤? – xeon48

回答

24

AngularJs < 1.6

試圖通過給成功和失敗的回調:

$http.get('someFile.json') 
     .success(function(data) { 
      angular.extend(_this, data); 
      defer.resolve(); 
     }) 
     .error(function() { 
      defer.reject('could not find someFile.json'); 
     }); 

AngularJs> 1.6

$http.get('someFile.json'). 
    then(function onSuccess(response) { 
    angular.extend(_this, data); 
    defer.resolve(); 
    }). 
    catch(function onError(response) { 
    console.log(response); 
    }); 

參見:Read local file in AngularJS

+3

。成功已棄用。改用;然後;) – LOTUSMS

1

如果你還沒有這樣做。嘗試爲您的應用程序設置crossdomain策略。

2

難道你沒有像「$ http:is not defined」這樣的錯誤信息嗎?

我試圖用一個控制器,這是工作:

var ngApp = angular.module("ngApp", []); 

ngApp.controller('myController', ['$http', function($http){ 
    var thisCtrl = this; 

    this.getData = function() { 
    this.route = 'webtest.json'; 
    $http.get(thisCtrl.route) 
    .success(function(data){ 
     console.log(data); 
    }) 
    .error(function(data){ 
     console.log("Error getting data from " + thisCtrl.route); 
    }); 
    } 
}]); 

如果你還沒有,使用的Web開發工具(按Ctrl + Shift + I在Firefox)。

+1

我得到這個錯誤 - > XMLHttpRequest無法加載file:/// C:/Users/Handson/webtest.json。只有協議方案支持跨源請求:http,data,chrome,chrome-extension,https,chrome-extension-resource – Amit

+0

我想這是因爲你沒有權限訪問本地文件(安全原因)。您應該使用本地Web服務器(如apache)來避免這種錯誤。 – Pico12

相關問題