Jquery: Ajax call to servlet & get data as json

前端 未结 1 523
予麋鹿
予麋鹿 2021-02-06 10:26

I\'m newbie on servlet and I need to get data from database to display chart

 $.ajax({
     url : \"NameServlet\",
     dataType : \'json\',
     error : func         


        
相关标签:
1条回答
  • 2021-02-06 11:04

    so here is the answer

    you jquery to push data to your variable

    $.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);
    
                            }); 
                    });
    
                }
            });
    

    after this you need servlet to get JSON object

    Servlet would be like

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

    Hope this helps

    0 讨论(0)
提交回复
热议问题