为什么本地Json文件内容没有显示在html页面中?

时间:2017-02-24 17:27:45

标签: javascript html angularjs json

我想通过使用AngularJs(ng-Reapeat)来显示json文件的内容我的问题是html页面无法显示Json文件的内容而且它是空白的!!我在我的本地驱动器上有这个Json文件,名称为JsonData.json。我也更改了文件的地址,但它不起作用。

这是我的代码:

<!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 个答案:

答案 0 :(得分:2)

在许多(并非所有)浏览器中,从file://网址投放的网页无法对file://网址进行ajax调用;这违反了Same Origin Policyfile://网址都定义为原点“null”,与任何内容都不匹配。

当然,http://提供的服务无法访问file://路径,因为它根据定义是跨域的,file://网址无法提供Cross-Origin Resource Sharing标头,因为没有涉及Web服务器。

解决方案:从本地Web服务器进行测试,而不是通过文件资源管理器打开的文件。