首页 > 解决方案 > 从 ajax jquery 迁移到 angularjs $http

问题描述

我正在将我的项目从 ajax jquery 迁移到 angularjs。其中我的代码的目标是将 json 对象显示到 html 表中。

我已经尝试了一些示例代码来使用 angularjs 显示 json 数据/对象,但它仍然不起作用。

这是我在 ajax jquery 中的代码:

    $.ajax({
        type:"GET",
        datatype:"json",
        url:"http://localhost:7878/server/getrecords",
        success: function(){
            //alert("Successful!");
        }
    }).then(function(json){
        var user = json;
        console.log(user);
        $.each(json, function(key, value){
            var strappend = '<tr><td>' + value.billingCycle + '</td>'
            + '<td>' + value.startDate + '</td>' 
            + '<td>' + value.endDate + '</td>'
            + '<td>' + value.customerFirstName + '</td>'
            + '<td>' + value.customerLastName + '</td>' 
            + '<td>' + value.amount + '</td></tr>';
            $("table tbody").append(strappend);
            console.log(key);

        });
    });
});

我希望预期的输出在 html 表中显示所有报告。我希望你能帮助我。谢谢!

标签: angularjsajaxrestspring-boot

解决方案


如果您在控制器中执行此操作:

$http({
  method: 'GET',
  url: 'http://localhost:7878/server/getrecords'
}).then(function(response) {
  try {
    $scope.users = JSON.parse(response.data);
  } catch (e) {}
});

在模板中:

...
<tr ng-repeat="user in users">
  <td>{{user.billingCycle}}</td>
  <td>{{user.startDate}}</td> 
  <td>{{user.endDate}}</td>
  <td>{{user.customerFirstName}}</td>
  <td>{{user.customerLastName}}</td> 
  <td>{{user.amount}}</td>
</tr>
...

更好的方法是使用方法创建服务,getrecords并且在控制器中只需从服务中调用此方法


推荐阅读