【发布时间】:2015-04-07 20:48:19
【问题描述】:
我是 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 文件位于同一文件夹中。
【问题讨论】:
-
当您在回调中使用 console.log(typeof response) 时会显示什么?是字符串还是对象?
-
强制是文本文件而不是json文件吗?
-
文件格式为json。只有它的扩展名是.txt,另外我还需要拉一些文本文件。
-
@nanndoj 我认为它不会进入任何这些成功()或错误()函数
-
澄清一下,你在那个文本文件中的 json 是一个数组?
标签: javascript json angularjs text xmlhttprequest