【发布时间】:2016-03-30 04:35:24
【问题描述】:
我为我正在开发的应用程序编写了一个 Flask 后端。简而言之,当调用 http://localhost:5000/allsongs/ 时,它会返回类似(或非常相似)以下内容:
[["King And Lionheart", "Of Monsters And Men", "My Head Is An Animal", "mp3"], ["Just One Yesterday", "Fall Out Boy", "Save Rock And Roll", "mp3"], ["Laughter Lines", "Bastille", "All This Bad Blood", "mp3"]]
我正在尝试使用 AngularJS 编写一个网络应用程序,该应用程序从该 URL 读取数据并使用 ng-repeat 来创建一个我可以搜索的列表。到目前为止,我已经写了这个:
<!DOCTYPE html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<html ng-app="myApp">
<body>
<script>
angular.module('myApp', [])
.controller('Songs', function Songs($scope, $http) {
$http.get('http://localhost:5000/allmusic').then(function(response) {
$scope.songs = response;
});
}
);
</script>
<input placeholder="Search..." type="text" ng-model="search" />
<div ng-controller="Songs">
<p>{{songs}}</p>
</div>
<p ng-repeat="song in songs | filter:search | orderBy:name">{{ song }}</p>
</body>
</html>
加载页面时显示的只是页面顶部的搜索字段。
另外,当我刷新页面时,我看到我的 Flask 服务器被调用,所以我知道 $http.get 正在工作。
任何建议都会很棒!
【问题讨论】:
-
哎呀,ng-repeat 复制粘贴错了,原来是:
<div ng-controller="Songs"><p ng-repeat="song in songs | filter:search | orderBy:name">{{ song }}</p></div> -
你不应该使用 $scope.songs = JSON.parse(response)
-
您是否对 then 函数内的 $http.get 响应执行了 console.log 以验证您是否获得了预期的数据?
-
@Ludo - 如果响应已经是来自服务器的 json 格式,则不需要解析响应。它将在 Angular 中直接可用和分配。
-
@DanielNalbach - 我为响应添加了一个 console.log,但我发现了这个:
XMLHttpRequest cannot load http://localhost:5000/allmusic. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.,在删除 console.log 时它仍然存在。简单来说,日志什么也没做,但是那个错误就在那里。
标签: javascript python html angularjs json