我是新來AngularJS並試圖從一個文本文件讀取JSON數據:充分利用在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';
});
這沒有顯示任何內容。現在,如果我取代與分配給$ test.txt的數據上面的http請求scope.names然後開始工作:我的意思是,像這樣:
$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 = [
最後分號;
這意味着$ HTTP請求test.txt的失敗是在同一文件夾中的HTML和JS文件。任何人都可以請幫助。
感謝。
=======更新========
有兩個問題。
- 我在我的控制器功能中遺漏了$ http參數。
- 我所用「POST」,這是我替換爲「GET」,使其工作
現在從本地計算機和遠程Web服務器的工作。
感謝您的幫助。
當您在回調中使用console.log(typeof response)時會顯示什麼?它是一個字符串還是一個對象? – nanndoj 2015-02-07 21:05:16
強制它是一個文本文件而不是json文件嗎? – squiroid 2015-02-07 21:11:12
文件格式是json。只有它的擴展名是.txt,另外我還需要提取一些文本文件。 – Anjum 2015-02-07 21:12:52