[英]how can i get json data from java servlet to jquery
这是我的servlet:json数组具有对象“ esquina”。 esquina具有两个属性double coordX和double coordY
package servlets;
@WebServlet("/Mapa")
public class ServletMapa extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ServletMapa() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Sistema instanciaSys = Sistema.darInstancia();
instanciaSys.inicializarSistema(6);
Esquina[] esquinas = instanciaSys.getEsquinas();
JSONArray json =new JSONArray();
JSONObject jO = null;
for (Esquina esquina : esquinas) {
jO = new JSONObject(esquina);
json.put(jO);
System.out.println(json);
}
request.setAttribute("esquinas", esquinas);
request.setAttribute("json", json);
request.getRequestDispatcher("/gui/Mapa.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
我需要将数据从jsonArray获取到jquery,我尝试了getJSON()函数,但没有工作。
这是代码
function cargarMarcadores() {
var x=$("#iniSistema");
x.click(function(){
$.getJSON('localhost:8080/Carpuleame/Mapa',function(data){
alert("data");
});
});
}
有另一种方法吗?
您可能想要这样的东西:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Sistema instanciaSys = Sistema.darInstancia();
instanciaSys.inicializarSistema(6);
Esquina[] esquinas = instanciaSys.getEsquinas();
JSONArray json =new JSONArray();
for (Esquina esquina : esquinas) {
JSONObject jO = new JSONObject();
jO.put("coordX", esquina.getCoordX());
jO.put("coordY", esquina.getCoordY());
json.put(jO);
}
// tell the client that JSON is coming
response.setContentType("application/json");
resposne.setCharacterEncoding("UTF-8");
json.write(response.getWriter());
}
有许多框架可以消除此代码的许多“蛮力”性,但这与您的开始位置非常接近。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.