问题
Below is my JSP page (abc.jsp)
from which I am calling another JSP page jspConnection.jsp
using the jQuery and then jspConnection.jsp
will return me back the query result to abc.jsp
and then I need to use the result to show them in a table -
Below code I have in abc.jsp from which I am calling jspConnection.jsp -
$.post("jspConnection.jsp", {'id': id},
function (data) {
// make a new table here from JSONObject
// and show the result here
}
);
Table should look like this in abc.jsp after iterating the JSONObject -
FirstName LastName Address Email PhoneNumber
SomeValue SomeOtherValue SomeOtherValue SomeOtherValue SomeOtherValue
... ... ... .... ....
... ... ... .... ....
Now below is the jspConnection.jsp
from which I am returning the result of my sql query to abc.jsp
page. My SQL query will return me multiple rows.
Below is my sql query which I am executing -
SELECT FirstName, LastName, Libs, Email, PhoneNumber from Testing;
Now I need to return a JSON Object of my above SELECT query -
JSONObject obj = new JSONObject();
JSONArray list = new JSONArray();
while (resultSet.next()) {
// This might be wrong way to make an object for my scenario
obj.put("FirstName", rs.getString(1)) ;
obj.put("LastName", rs.getString(2)) ;
obj.put("Address", rs.getString(3)) ;
obj.put("Email", rs.getString(4)) ;
obj.put("PhoneNumber", rs.getString(5)) ;
}
list.add(obj);
response.getWriter().write(obj.toString());
Now I am not sure how to return the JSONObject such that I can make the table in abc.jsp correctly.. As currently the way I am making JSONObject and JSONArray is not right I guess so not able to understand how to do it correctly?
回答1:
You need to create a new JSONObject
at the beginning of each iteration, and you must add it to your JSONArray
at the end of each iteration. Perhaps like this,
JSONArray list = new JSONArray();
while (resultSet.next()) {
JSONObject obj = new JSONObject(); // Move this here.
// This might be wrong way to make an object for my scenario
obj.put("FirstName", rs.getString(1));
obj.put("LastName", rs.getString(2));
obj.put("Address", rs.getString(3));
obj.put("Email", rs.getString(4));
obj.put("PhoneNumber", rs.getString(5));
list.add(obj); // And this here.
}
来源:https://stackoverflow.com/questions/21069952/how-to-pass-the-jsonarray-from-one-jsp-to-another-jsp-and-show-the-results-in-ta