我是AngularJS的新手并尝试从文本文件中获取JSON数据:
这是我的HTML:
<div ng-controller="customersController as custCont">
<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
我的控制器如下:
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';
});
这没有显示任何内容。现在,如果我用分配给$ 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"
}
];
文本文件显然包含除第一行以外的所有数据(即$scope.names = [
和最后一个分号;
这意味着对test.txt的$ http请求失败,该请求与HTML和JS文件位于同一文件夹中。
答案 0 :(得分:5)
您缺少将$ http定义为参数
app.controller( "customersController", function( $scope, $window, $http) {
还要确保您在Web服务器中进行测试。你不能从file:// protocol
发出ajax请求同时将您的请求从POST更改为GET,它应该可以正常工作。 Here is a Punklr
method: 'GET',
答案 1 :(得分:0)
(代表问题作者发布的答案)。
有两个问题。
它现在可以在本地计算机以及远程Web服务器上运行。