我有这段代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter printWriter = response.getWriter();
JSONArray arrayObj=new JSONArray();
TimeTableDAO timeTable = new TimeTableDAO();
ArrayList<String[]> data = timeTable.getTimeTableData();
for (int i = 0; i < data.size(); i++){
for (int j = 0; j < data.get(i).length; j++){
printWriter.print("Token " + data.get(i)[j] + "\n");
}
}
response.sendRedirect("script.js");
response.getWriter().write(data.toString());
}
在我的javascript文件中, 一旦页面被加载并且所有内容都被呈现,它将触发它:
$(window).on('load', function() {
$.get("TeacherServlet", function(response) {
console.log(response);
});
});
我正在尝试将我在servlet中的数据传递回javascript,以便我可以使用Jquery对数据执行其他操作。 但是我希望这些数据作为JSON格式传回。
请有人帮我这样做。在此先感谢:)
答案 0 :(得分:1)
然后将所有内容添加到JSONArray中,然后将其写入响应
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter printWriter = response.getWriter();
JSONArray arrayObj=new JSONArray();
TimeTableDAO timeTable = new TimeTableDAO();
ArrayList<String[]> data = timeTable.getTimeTableData();
for (int i = 0; i < data.size(); i++){
for (int j = 0; j < data.get(i).length; j++){
arrayObj.put(data.get(i)[j]); // instead of writing directly, add it to the JSONArray.
}
}
printWriter.println(arrayObj.toString()); //write the JSONArray to the response
response.sendRedirect("script.js");
//response.getWriter().write(data.toString()); //this doesn't do what you want
}
答案 1 :(得分:0)
您有很多问题:
RequestDispatcher
对象获取request
并将请求分派给目标资源(在您的情况下,是js文件)。修改强>
其他信息。
HttpServletRequest
是一个很好的起点。request.setAttribute(attributeName, attributeValue);
request.getRequestDispatcher(stringPathToTargetResource);