[英]Angular display response in HTML from Ajax GET
事先向您提出一个愚蠢的问题。 我已经发表了十几篇相关文章,但都没有成功。
这是我的控制器。
app.controller('testController', function ($scope) {
var myApi = 'https://jsonplaceholder.typicode.com/posts';
$.ajax({
url: myApi,
type: 'GET',
success: function (response) {
console.log(response[0]);
$scope.response = response[0]
},
error: function (response) {
console.log("could not retrieve list.");
console.log(response.message);
}
});
});
我的HTML是
<body ng-app="myApp" class="text-center">
<div id="foo" ng-controller="testController">
{{response.title}}
</div>
...
</body>
而且我可以在浏览器控制台中看到我确实在GET响应中获得了所需的内容
[Log] {userId: 1, id: 1, title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body: "quia et suscipit↵suscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto"} (javascript.js, line 27)
...但是文本不会显示在呈现的HTML中。 我究竟做错了什么?
在这里回答我的后代问题。 我从Ajax切换到此$ http方法。 如您所知,我对此是超级全新的。 如果有经验丰富的专家正在阅读本文,您可以在这里对两种方法进行评论,并描述我可能缺少的任何内容吗?
app.controller('testController', function ($scope, $http) {
$http({
method: 'GET',
url: 'https://jsonplaceholder.typicode.com/posts',
}).then(function (response) {
console.log(response.data[0])
$scope.response = response.data[0];
console.log($scope.response)
//alert($scope.response);
});
});
<body ng-app="myApp" class="text-center">
<div id="foo" ng-controller="testController">
{{response.title}}
</div>
...
</body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.