6

我是 servlet 的新手,我需要从数据库中获取数据以显示图表

 $.ajax({
     url : "NameServlet",
     dataType : 'json',
     error : function(){
        alert("Error Occured");
     },
     success : function(data) {
        var receivedData = [];
    //how to put data in var (i.e. receivedData) which is received from servlet
     }
    });

什么是我的servlet来获取数据

4

1 回答 1

6

所以这是答案

你 jquery 将数据推送到你的变量

$.ajax({

            url : "NameServlet",
            dataType : 'json',
            error : function() {

                alert("Error Occured");
            },
            success : function(data) {
                var receivedData = [];

                $.each(data.jsonArray, function(index) {
                    $.each(data.jsonArray[index], function(key, value) {
                        var point = [];

                            point.push(key);
                            point.push(value);
                            receivedData.push(point);

                        }); 
                });

            }
        });

在此之后,您需要 servlet 来获取 JSON 对象

Servlet 就像

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class NameServlet extends HttpServlet {

        int []sampleData=null;
        //sampleData= here you can get data from database

        //writing data to json
        response.setContentType("application/json;charset=utf-8");

        JSONObject json = new JSONObject();
        JSONArray array = new JSONArray();
        JSONObject member =  new JSONObject();

        member.put("arrayData", sampleData);
        array.add(member);

        json.put("jsonArray", array);

        PrintWriter pw = response.getWriter(); 
        pw.print(json.toString());
        pw.close();

}

希望这可以帮助

于 2012-09-26T11:43:21.437 回答