2017-02-24 46 views
0

我想通過使用AngularJs(ng-Reapeat)顯示json文件的內容我的問題是,html頁面無法顯示Json文件的內容,它是空白的!我在本地驅動器上有名爲JsonData.json的Json文件。我也改變了文件的地址,但它不起作用。爲什麼本地Json文件內容未在html頁面中顯示?

這裏是我的代碼:

<!DOCTYPE html> 
<html> 
    <head> 
     <title></title> 
     <script src="Scripts/angular.js"></script> 
     <script> 

      var test = angular.module("myApp", []); 
      test.controller("customersCtrl", function ($scope, $http) { 
       $http.get("~/Models/JsonData.json").success(function (response) { $scope.names = response.data.records; }); 
      }); 
     </script> 

    </head> 
    <body> 
     <div ng-app="myApp"> 
      <div ng-controller="customersCtrl"> 
       <table> 
        <tr ng-repeat="x in names"> 
         <td>{{ x.Name }}</td> 
         <td>{{ x.Country }}</td> 
        </tr> 
       </table> 
      </div> 
     </div> 
    </body> 
</html> 

,這是我的JSON文件:

{ 
    "records": [ 
    { 
     "Name": "Alfreds Futterkiste", 
     "City": "Berlin", 
     "Country": "Germany" 
    }, 
    { 
     "Name": "Berglunds snabbköp", 
     "City": "Luleå", 
     "Country": "Sweden" 
    }, 
    { 
     "Name": "Wolski Zajazd", 
     "City": "Warszawa", 
     "Country": "Poland" 
    } 
    ] 
} 
+1

控制檯devtools上的任何錯誤? – lealceldeiro

+2

這是一個CORS問題 - 您不希望您的瀏覽器訪問您的本地文件系統,是嗎? – chazsolo

+1

on $'http.get(「〜/ Models/JsonData.json」)。success(function(response){$ scope.names = response.data.records;});''response''實際上是您的響應數據,而不是響應本身,因爲你使用'success'而不是'then' – lealceldeiro

回答

2

在許多(不是所有)瀏覽器,從file:// URL提供服務的頁面無法讓AJAX調用file://網址;這違反了Same Origin Policyfile://網址全部被定義爲具有不匹配任何內容的原始「null」。

和當然,一個從http://提供服務,因爲它是跨起源定義和file://的URL不能提供Cross-Origin Resource Sharing頭,因爲有沒有涉及Web服務器不能訪問file://路徑。

解決方案:從本地Web服務器執行測試,而不是通過文件資源管理器打開的文件。