【问题标题】:how can i get json data from java servlet to jquery我如何从 java servlet 到 jquery 获取 json 数据
【发布时间】:2015-11-13 01:21:29
【问题描述】:

这是我的 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");
                });
            });

}

还有其他方法吗?

【问题讨论】:

    标签: java jquery json servlets


    【解决方案1】:

    你可能想要这样的东西:

    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());
    }
    

    有很多框架可以消除这段代码的很多“蛮力”,但这非常接近你的起始位置。

    【讨论】:

    • 谢谢,我需要那些坐标来放置一个标记(谷歌地图 api)。
    • 酷。如果我解决了您的问题,请考虑接受答案。
    猜你喜欢
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    相关资源
    最近更新 更多