gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:00:45 24 4
gpt4 key购买 nike

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

这是我的 HTML:

<div ng-controller="customersController as custCont"> 
<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>

而我的 Controller 如下所示:

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 文件位于同一文件夹中。

最佳答案

您缺少将 $http 定义为参数

app.controller( "customersController", function( $scope, $window, $http) {

还要确保您在网络服务器中进行测试。你不能从 file://协议(protocol)发出 ajax 请求

同时将您的请求从 POST 更改为 GET,它应该可以正常工作。 Here is a Punklr

 method: 'GET',

关于javascript - 从 AngularJS 中的文本文件获取 Json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28387312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com