【问题标题】:Fetch data using angularJS $get使用 angularJS $get 获取数据
【发布时间】:2013-09-10 04:47:54
【问题描述】:

我正在尝试使用 Angular 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/

【问题讨论】:

  • 使用 Django 模板和 Angular 对我来说似乎不是一个好主意:(。你可以用 Angular 模板完全替换 Django MTV 中的模板。

标签: javascript django angularjs


【解决方案1】:

$https xhr 回调方法(then、success、error)的参数应该是回调函数,而不是您所做的表达式。试试这个:

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

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

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

【讨论】:

  • 现在我收到警报“未定义”并且我的模板有重复的内容:(
  • 表示response.revenue未定义。重复正是我对这个问题的评论。我没有检查您的 django 模板,但似乎也在页面上显示响应以及角度模板。只使用其中一种。
  • 我是 Angular 新手,你能修复那部分吗:)
【解决方案2】:

参考the doc.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;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-30
    • 2018-10-17
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多