首页 > 解决方案 > AngularJS $http 没有将变量更新为 JSON 结果?

问题描述

我的 html 代码中有以下内容。

</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js">

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
        $http({
            method : "GET",
            url : "localhost:5000"
        }).then(function mySuccess(response) {
            $scope.myWelcome = response.data;
            console.log($scope.myWelcome)
        }, function myError(response) {
            $scope.myWelcome = response.statusText;
        });
    });
</script>


<div ng-app="myApp" ng-controller="myCtrl">

    <p>Response of JSON Below:</p>
    <h1>{{myWelcome}}</h1>

</div>

在此之后它只是在 HTML 中说 {{myWelcome}} 它应该说已经设置并且正在工作的 JSON 的响应。

不知道是什么问题。

当我仅使用我得到的方法将脚本作为独立的 .JS 文件单独运行时

角度未定义

但这就是为什么我包括

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js">

JSON由python生成,看起来像这样

{"text": "Hello World!"}

有任何想法吗?

使用 Angular JS

标签: angularjshttp

解决方案


使用两个脚本元素:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js">
</script>

<script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
        $http({
            method : "GET",
            url : "localhost:5000"
        }).then(function mySuccess(response) {
            $scope.myWelcome = response.data;
            console.log($scope.myWelcome)
        }, function myError(response) {
            $scope.myWelcome = response.statusText;
        });
    });
</script>

从文档:

如果脚本元素具有src指定的属性,则不应在其标签中嵌入脚本,因为它可能导致意外行为。意外行为是因为只有src属性中引用的文件中的 JavaScript 才会添加到 HTML 页面。

有关详细信息,请参阅


推荐阅读