jquery ajax调用servlet方法并返回json数据

时间:2013-11-02 06:16:33

标签: java jquery ajax json servlets

我是Ajax编程新手我正在使用Jquery ajax将数据提取到服务器并以表格格式显示。在该位置必须显示单选按钮类型。 如何调用servlet特定的方法如何返回data.i我准备使用json.can任何一个帮我如何调用一个方法如何返回一个data.and建议需要解决问题

提前谢谢。

$('#ajaxbutton').on('click',function(){
                $.ajax({
                    type:"post",
                    url:"Db2",
                    data:{"labid",100},
                    sucess:function(){
                        alert("sucess");
                    }

                });
            });

在servlet中

public class Db2 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws MalformedURLException, IOException {
        doProcess(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws MalformedURLException, IOException {
        doProcess(request, response);
    }

    public void doProcess(HttpServletRequest request,
            HttpServletResponse response) throws MalformedURLException,
            IOException {
        Connection con;
        PreparedStatement ps, ps1;
        PrintWriter out = response.getWriter();

        try {

            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con = DriverManager.getConnection("jdbc:odbc:oracle1", "system",
                    "sarath");
            ps = con.prepareStatement("select trackid,location,to_char(mydate,'dd-mon-yyyy') from information where labid=100");
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                String location = rs.getString(2);
                String track = rs.getString(1);
                String myDate = rs.getString(3);
            }

        } catch (Exception e) {
            out.println(e);
        }

    }
}// end of ServletB

2 个答案:

答案 0 :(得分:2)

如何调用servlet特定方法 在你的ajax中你正在编写type=post所以在servlet doPost()中将被调用。如果它是type=get那么将调用servlet doGet()方法。所以你应该写数据库检索特定方法中的部分。

现在假设你想要位置,跟踪和mydate然后尝试这种方式 在servlet中

PrintWriter out.response.getWriter();
out.println(location);
out.println(track);
out.println(mydate);

在ajax成功部分这样做

success: function(data, textStatus, jqXHR){
                       alert(data); 

答案 1 :(得分:0)

PrintWriter out = response.getWriter();
StringBuffer res = new StringBuffer();
while (rs.next()) {
    String location = rs.getString(2);
    String track = rs.getString(1);
    String myDate = rs.getString(3);
    res.append("{");
    res.append("'location':");
    res.append(location);
    res.append(",");
    res.append("'track':");
    res.append(track);
    res.append(",");
    res.append("'myDate ':");
    res.append("myDate ");
    res.append("}");
}
out.println(res.toString());

必须是json-string,ajax可以使用eval("data = "+r_data+";");