我在W3Schools上找到的关于Angular服务的示例遇到了麻烦,在这个特定情况下$http.get 一个。
我有一个 json.php 文件,其中有下一个 JSON:
{
"bands": [
{
"name": "Red hot chilli peppers",
"year": "2009",
},
{
"name": "Maroon 5",
"year": "2005",
},
{
"name": "ACDC",
"year": "2000",
}
]
}
以及应该遍历对象并显示其中数据的 Angular 和 HTML 代码,但它不起作用:
JavaScript
var serviceTestApp = angular.module('myapp3', []);
serviceTestApp.controller('controller3', function($scope, $http){
$http.get('json.php').then(function(response){
$scope.myData = response.data.bands;
});
});
.HTML
<div ng-app='myapp3' ng-controller='controller3'>
<ul>
<li ng-repeat='x in myData'>
{{x.name}}
</li>
</ul>
</div>
我在这里做错了什么?我使用 Angular 1.5.0
当你的意思是不工作时,你到底是什么意思?你的意思是它成功了,但没有返回你想要的?在这种情况下,您可能指向对象中的错误内容。还是抛出错误?
你应该像这样构建它:
$http.get('json.php').then(function(response){
// Place a debugger statement here to see if it's successful
$scope.myData = response.data.bands;
}, function(error) {
// No breakpoint needed as you'll see the error in the console window
console.error(error);
});
另一个原因可能是您没有将文件放在正确的位置。 json.php
意味着我希望它与控制器位于同一文件夹中。