AngularJS - http获取响应(JSON数组)并以html格式显示

时间:2016-10-07 05:04:11

标签: java angularjs arrays json servlets

我在Java中创建了一个使用;

显示数组的servlet
    printWriter.println(jsonarray);

数组显示在servlet页面上,但这就是乐趣停止的地方。我想使用AngularJS将数组显示为网页上的表格,我以前没有这方面的经验。但我无法在网页上显示数组,更不用说将其显示为表格了

HTML

    <div ng-app="myApp" ng-controller="myController">{{myArray}}</div>

AngularJS

var app = angular.module("myApp", []);

app.controller("myController", function($scope, $http)
{
    $scope.recipes = null;
    $scope.message = null;
    $scope.filterString = '';
    $scope.sortByName = false;
    $scope.sortOrder = '';
    $scope.setSortOrder = function()
    {
        if($scope.sortByName)
        {
            $scope.sortOrder = 'name';
        }
        else
        {
            $scope.sortOrder = '';
        }
    }


    var connection = $http(
    {
        method: 'GET',
        url: 'http://localhost:8080/students'
    })


    .then(function(response)
    {
        $scope.myArray = response.data;
    })
    .catch(function(response)
    {
        // It is OK not to take any action here because it would be
        // clear to the user if the list operation is succesfull or not
    })

    .finally(function(config)   // induce a syntax error here and see what happens
    {
        // It is OK not to take any action here because it would be
        // clear to the user if the list operation is succesfull or not
    });


});
//end controller

好的,修正了一些小错误,但现在我找不到404文件错误

http://localhost:8080/students

当我访问浏览器中的链接时,我显示了数组,但网页正在给我;

404 Error Image

更改angular.js版本修复了404,我之前的版本是1.4.8

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>

2 个答案:

答案 0 :(得分:0)

尝试:

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

  <table>
    <tr ng-repeat="x in myArray">
      <td>{{ x.name }}</td>
      <td>{{ x.age }}</td>
    </tr>
  </table>

</div>

答案 1 :(得分:0)

尝试ng-repeat指令。

ng-repeat指令重复一组HTML,给定次数。

系列中的每个项目都会重复一次HTML。

该集合必须是arrayobject

语法:

<div ng-repeat="item in myArray"></div>

根据您的要求回答:

<div ng-app="myApp" ng-controller="myController"> 
  <table>
    <tr>
      <td>Name</td>
      <td>Age</td>
    </tr>
    <tr ng-repeat="item in myArray">
      <td>{{::item.name}}</td>
      <td>{{::item.age}}</td>
    </tr>
  </table>
</div>

就您遇到的第二个问题而言,看起来您传入ajax调用的网址无效。

404代码表示服务器无法通过GETPOST请求找到您要查找的文件。