2016-12-01 33 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響應」 –