我正在尝试使用 JSONObject 和 JSONArray 将 json 数组从我的 java servlet(使用 mysql 服务器)发送到 html 页面。数组已成功发送到 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 中找到的唯一内容是如何使用 AngularJS 从 json 文件填充表格。我可能在设置 AngularJS 脚本代码时遇到问题,但我真的不知道在这种情况下该怎么做。非常感谢对此问题的任何帮助!
OBS,我不使用JSP。
最佳答案
根据您最后的评论,您在写回回复时似乎缺少 content-type : application/json
。你的 Angular 设置看起来很好。没有问题...
JSONObject json1 = new JSONObject();
json1.put("Info", jarr);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json1.toString());
rs.close();
关于java - 如何使用 AngularJS 从 Java 的 JSONArray 填充 html 表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40917701/