【问题标题】:AngularJS - http get response (JSON Array) and display in htmlAngularJS - http 获取响应(JSON 数组)并以 html 显示
【发布时间】:2017-02-16 00:16:49
【问题描述】:

我在 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>

【问题讨论】:

  • 您是否遇到任何错误,请检查浏览器开发控制台上的网络选项卡。

标签: java angularjs arrays json servlets


【解决方案1】:

试试:

<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>

【讨论】:

    【解决方案2】:

    试试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 调用的 url 似乎无效。

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

    【讨论】:

    • localhost:8080/recipeWS/recipes 是正确的网址,但我仍然收到 404 错误
    • @user3121518 但根据您的错误 sn-p http://i.stack.imgur.com/VoVme.png 请求网址不同。
    • 根据您更新的问题,我认为问题已经解决。如果您认为这个问题对您和其他人都有益,请将其标记为正确。
    猜你喜欢
    • 2021-05-07
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多