使用 angularJS $get获取数据

Fetch data using angularJS $get

本文关键字:获取 数据 get angularJS 使用      更新时间:2023-09-26

我正在尝试使用角度 js $get来获取数据。我可以使用这样的简单功能来做到这一点:

 <script>
    $(document).ready(function() {
        $.getJSON('{% url 'ajax-view' %}', function(data) {
            alert(data['revenue']);
        })
    })

</script>

but trying this way in angular. since im new to this. cant get it work.

      <script>
        var app = angular.module('plinc', []);
        app.controller('MainCtrl', function($scope, $http) {
        $http({
        url: '{% url 'ajax-view' %}',
        method: "GET"
        }).then($scope.getdata = function(response) {
        alert(data['revenue']);
        $scope.data = response;
        });
        });
        </script>

这是完整的 Django 模板: https://dpaste.de/4Y3y5/

$http 的 xhr 回调方法(然后,成功、错误)的参数应该是一个回调函数,而不是像你所做的那样是一个表达式。试试这个:

.then(function(response) {
    alert(response['revenue']);
    $scope.data = response;
});

注意:您也可以使用$http.get(url)而不是更详细的

$http({'method': 'GET', 'url': url})语法。

引用文档,.then().success()注册的回调具有不同的签名:

.success(function(data, status, headers, config) {})
// Here response is like {data:..., status:..., headers:..., config:...}
.then(function(response) {})

因此,您的代码可能是

$http.get('{% url 'ajax-view' %}').then(function(response) {
    alert(response.data.revenue);
    $scope.data = response.data;
});

$http.get('{% url 'ajax-view' %}').success(function(data) {
    alert(data.revenue);
    $scope.data = data;
});