Mo Sharaf
Mo Sharaf

Reputation: 5

Why Local Json file content is not shown in html page?

I want to show the content of json file by using AngularJs (ng-Reapeat) My problem is that the html page cannot show the content of Json file and it is blank!! I have this Json file on my local drive with name, JsonData.json. I have also change the address of the file but it does not work.

here is my code:

<!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>

and this is my Json File:

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

Upvotes: 0

Views: 53

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

In many (not all) browsers, a page served from a file:// URL cannot make ajax calls to file:// URLs; it's a violation of the Same Origin Policy. file:// URLs are all defined to have origin "null" which doesn't match anything.

And of course, one served from http:// can't access a file:// path because it's cross-origin by definition and file:// URLs can't offer Cross-Origin Resource Sharing headers, as there's no web server involved.

Solution: Do your testing from a local web server, not files you open via your file explorer.

Upvotes: 2

Related Questions