无法访问JSON文件存在于同一文件夹中:AngularJS

时间:2015-11-20 09:11:24

标签: json angularjs xmlhttprequest

我尝试使用JSON文件,JSON文件与我的HTML文件存在于同一文件夹中。

<html ng-app="countryApp">
  <head>
    <meta charset="utf-8">
    <title>Angular.js Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <script>
      var countryApp = angular.module('countryApp', []);
      countryApp.controller('CountryCtrl', function ($scope, $http){
        $http.get('countries.json').success(function(data) {
          $scope.countries = data;
        });
      });
    </script>
  </head>
  <body ng-controller="CountryCtrl">
    <table>
      <tr>
        <th>Country</th>
        <th>Population</th>
      </tr>
      <tr ng-repeat="country in countries">
        <td>{{country.name}}</td>
        <td>{{country.population}}</td>
      </tr>
    </table>
  </body>
</html>

但是当我加载我的HTML文件时,我收到一个控制台错误说:

  

XMLHttpRequest无法加载file://countries.json/。交叉起源   请求仅支持协议方案:http,data,chrome,   chrome-extension,https,chrome-extension-resource。

2 个答案:

答案 0 :(得分:1)

由于安全问题,您无法在localhost上加载javascript中的其他文件。尝试在http服务器上运行您的页面。

如果您有python,您只需在控制台中编写python -m SimpleHTTPServer 8000,其中工作目录是源文件夹,然后打开http://localhost:8000

答案 1 :(得分:1)

您可以做的是将$http.get('countries.json').success(function(data) {更改为此

$http.get("http://localhost:9009/yourFolderName/countries.json").then(function (data) {

假设您在端口9009上运行http本地服务器。