2016-12-01 61 views
1

我想从我的java servlet(使用mysql服务器)发送一个json数组到使用JSONObject和JSONArray的html页面。该数组已成功发送到HTML页面,但表本身没有得到任何东西。如何从Java的JSONArray中使用AngularJS填充html表格?

这是我总是得到的第一页的HTML页面和表本身没有得到任何东西。

{"Info":[{"Name":"Jack","Lastname":"Nilson","Birthday":"1980-10-10","Address":"Nowhere","State": "ABC","ZIP":"999"}]} 

的Servlet(的doPost)

conn = DriverManager.getConnection(url); 
     PreparedStatement ps = conn.prepareStatement("select* from db"); 
     ResultSet rs = ps.executeQuery(); 
     JSONArray jarr = new JSONArray(); 
     while(rs.next()){ 
      JSONObject obj = new JSONObject(); 
      obj.put("Name", rs.getString(1)); 
      obj.put("Lastname", rs.getString(2)); 
      obj.put("Birthday", rs.getDate(3)); 
      obj.put("Address", rs.getString(4)); 
      obj.put("State", rs.getString(5)); 
      obj.put("ZIP", rs.getInt(6)); 
      jarr.put(obj); 
     } 
     JSONObject json1 = new JSONObject(); 
     json1.put("Info", jarr); 

     response.getWriter().write(json1.toString()); 
     rs.close(); 

AngularJS:

<script type="text/javascript"> 
var app = angular.module('myApp', []); 
app.controller('customersCtrl', function($scope, $http) { 
    $http.post("InfoServletPath") 
    .then(function (response) { 
     $scope.Info = response.data.Info; 
    }); 
}); 
</script> 

HTML:

<body> 
    <form action="InfoServletPath" method="POST"> 
     <div ng-app="myApp" ng-controller="customersCtrl"> 
       <table id="pInfo"> 
        <thead> 
         <tr> 
          <th width="10%">Name</th> 
          <th width="10%">Lastname</th> 
          <th width="10%">Birthday</th> 
          <th width="10%">Address</th> 
          <th width="10%">STATE</th> 
          <th width="10%">Zip</th> 
         </tr> 
        </thead> 
        <tr ng-repeat="row in Info"> 
         <td> {{ row.Name }} </td> 
         <td> {{ row.Lastname }} </td> 
         <td> {{ row.Birthday }} </td> 
         <td> {{ row.Address }} </td> 
         <td> {{ row.State }} </td> 
         <td> {{ row.ZIP }} </td> 
        </tr> 
       </table> 
       </div> 
      </div> 
    </form> 
</body> 

我已经有这个问题几天了,老实说,我似乎无法找到任何解决方案的问题。我在互联网和stackoverflow上发现的唯一的事情是关于如何用json文件填充AngularJS的表格。我可能会遇到设置我的angularJS脚本代码的问题,但在这种情况下我不知道如何去做。任何对这个问题的帮助非常感谢!

OBS,我不使用JSP。

+0

你能分享你的承诺/响应内'console.log(response)'和'console.log(response.data)'的输出吗? – Searching

+0

@搜索'无效的JSON响应'是我得到的 –

+0

@搜索我很确定这个问题可能与我的angularjs代码有关,但我不完全确定问题出在哪里。嗯 –

回答

0

根据您的最新评论,您在回复回复时似乎缺少content-type : application/json。你角度设置看起来很好。没有问题那里...

JSONObject json1 = new JSONObject(); 
json1.put("Info", jarr); 

response.setContentType("application/json"); 
response.setCharacterEncoding("UTF-8"); 

response.getWriter().write(json1.toString()); 
rs.close(); 
+0

我已经在doPost函数的开头。 response.setContentType( “应用程序/ JSON;字符集= UTF-8”); –

+0

嗯......改为这个镜头,看看console.log是否仍然输出相同的错误? – Searching

+0

我刚把它移到你建议的路线上,仍然没有任何东西。相同的弹出式错误框“无效的JSON响应” –