从AngularJS中的文本文件中获取Json数据

AnR*_*AnR 2 javascript text json xmlhttprequest angularjs

我是AngularJS的新手并尝试从文本文件中获取JSON数据:

这是我的HTML:

<div ng-controller="customersController as custCont"> 
  <ul>
    <li ng-repeat="x in names">
      {{ x.Name + ', ' + x.Country }}
    </li>
  </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

而我的控制器如下所示:

app.controller( "customersController", function( $scope, $window) {
    $http({
        url: 'test.txt',
        dataType: 'json',
        method: 'POST',
        data: '',
        headers: {
            "Content-Type": "application/json"
        }

    }).success(function(response){
        $scope.names = response;
    }).error(function(error){
        $scope.names = 'error';
    });        
Run Code Online (Sandbox Code Playgroud)

这没有任何显示.现在,如果我用分配给$ scope.names的test.txt数据替换上面的http请求,那么它开始工作:我的意思是,像这样:

$scope.names = [
{
"Name" : "Alfreds Futterkiste",
"City" : "Berlin",
"Country" : "Germany"
},
{
"Name" : "Berglunds snabbköp",
"City" : "Luleå",
"Country" : "Sweden"
},
{
"Name" : "Centro comercial Moctezuma",
"City" : "México D.F.",
"Country" : "Mexico"
},
{
"Name" : "Ernst Handel",
"City" : "Graz",
"Country" : "Austria"
},
{
"Name" : "FISSA Fabrica Inter. Salchichas S.A.",
"City" : "Madrid",
"Country" : "Spain"
},
{
"Name" : "Galería del gastrónomo",
"City" : "Barcelona",
"Country" : "Spain"
},
{
"Name" : "Island Trading",
"City" : "Cowes",
"Country" : "UK"
},
{
"Name" : "Königlich Essen",
"City" : "Brandenburg",
"Country" : "Germany"
},
{
"Name" : "Laughing Bacchus Wine Cellars",
"City" : "Vancouver",
"Country" : "Canada"
},
{
"Name" : "Magazzini Alimentari Riuniti",
"City" : "Bergamo",
"Country" : "Italy"
},
{
"Name" : "North/South",
"City" : "London",
"Country" : "UK"
},
{
"Name" : "Paris spécialités",
"City" : "Paris",
"Country" : "France"
},
{
"Name" : "Rattlesnake Canyon Grocery",
"City" : "Albuquerque",
"Country" : "USA"
},
{
"Name" : "Simons bistro",
"City" : "København",
"Country" : "Denmark"
},
{
"Name" : "The Big Cheese",
"City" : "Portland",
"Country" : "USA"
},
{
"Name" : "Vaffeljernet",
"City" : "Århus",
"Country" : "Denmark"
},
{
"Name" : "Wolski Zajazd",
"City" : "Warszawa",
"Country" : "Poland"
}
];
Run Code Online (Sandbox Code Playgroud)

文本文件显然包含除第一行(即$scope.names = [最后一个分号)之外的所有数据 ;

这意味着对test.txt的$ http请求失败,该请求与HTML和JS文件位于同一文件夹中.

nan*_*doj 5

您缺少将$ http定义为参数

app.controller( "customersController", function( $scope, $window, $http) {
Run Code Online (Sandbox Code Playgroud)

还要确保您在Web服务器中进行测试.你不能从file:// protocol发出ajax请求

还要将您的请求从POST更改为GET,它应该可以正常工作.这是一个Punklr

 method: 'GET',
Run Code Online (Sandbox Code Playgroud)