I have a JSON string (using Gson) containing data from my database in a JSP file, and I want to pass this information to a JavaScript function.
JSP (consulta.jsp):
<%@ page language="java" import="java.sql.*" %>
<%@ page language="java" import="db.Conexao" %>
<%@ page language="java" import="java.util.ArrayList" %>
<%@ page language="java" import="com.google.gson.Gson" %>
<%
try {
// create connection instance
Conexao conexao = new Conexao("localhost", "app", "root", "diogo");
// connect to the database
Connection connection = conexao.connect();
// create statement and execute query
Statement st = connection.createStatement();
String sql = "SELECT * FROM crimes";
ResultSet rs = st.executeQuery(sql);
final ArrayList<String> id= new ArrayList<String>();
while(rs.next()) {
id.add("id");
id.add(rs.getString("id"));
id.add("latitude");
id.add(rs.getString("latitude"));
id.add("longitude");
id.add(rs.getString("longitude"));
}
String[] array = new String[id.size()];
array = id.toArray(array);
Gson gson = new Gson();
String json = gson.toJson(array);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
// close the database connection
connection.close();
}
catch(Exception e) {
out.println(e.toString());
}
%>
JS function:
function loadPoints() {
$.getJSON('consulta.jsp', function(points) {
$.each(points, function(index, point) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(LATITUDE VALUE HERE, LONGITUDE VALUE HERE),
title: value,
map: map,
icon: 'arma2.png'
});
}
}
PS:. The JSON string is ["id","1","latitude","-23.4831104000","longitude","-46.6330227000","id","4","latitude","-23.5874328731","longitude","-46.6573598700"]. Is it correct? Thank you.