Jquery:Ajax 调用 servlet 并以 json 形式获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12600827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:51:34  来源:igfitidea点击:

Jquery: Ajax call to servlet & get data as json

jqueryjsonservlets

提问by DamnCoder

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

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

what would be my servletto get data

什么是我的servlet来获取数据

采纳答案by Rahul P

so here is the answer

所以这就是答案

you jquery to push data to your variable

你 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);

                        }); 
                });

            }
        });

after this you need servlet to get JSON object

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

Servlet would be like

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

}

Hope this helps

希望这可以帮助