【问题标题】:Angular display response in HTML from Ajax GET来自 Ajax GET 的 HTML 中的角度显示响应
【发布时间】:2019-11-11 16:01:56
【问题描述】:

提前向您提出一个愚蠢的问题表示歉意。我已经关联了十几篇相关帖子,但均未成功。

这是我的控制器。

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 中。我做错了什么?

【问题讨论】:

    标签: javascript html angularjs ajax


    【解决方案1】:

    在这里为后代回答我自己的问题。我从 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>
    

    【讨论】:

    • AngularJS 通过提供自己的事件处理循环来修改正常的 JavaScript 流程。这将 JavaScript 拆分为经典和 AngularJS 执行上下文。只有在 AngularJS 执行上下文中应用的操作才能受益于 AngularJS 数据绑定、异常处理、属性监视等。$http 服务与 AngularJS 框架及其摘要循环集成。 jQuery .ajax 方法不是。
    猜你喜欢
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 2018-03-12
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    相关资源
    最近更新 更多