1

我是 Ajax 编程的新手,我正在使用 Jquery ajax 将数据提取到服务器并显示为表格格式。在该位置必须显示单选按钮类型。如何调用servlet特定方法如何返回数据。我已经准备好使用json了。任何人都可以帮助我如何调用方法如何返回数据。和建议需要解决问题

提前致谢。

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

                });
            });

在小服务程序中

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
4

2 回答 2

2

如何调用 servlet 特定方法 在您编写的 ajax 中,将调用 servlet。如果是,则将调用servlet方法。type=post因此,您应该在特定方法中编写数据库检索部分。doPost()type=getdoGet()

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

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

在ajax成功部分这样做

success: function(data, textStatus, jqXHR){
                       alert(data); 
于 2013-11-02T06:21:46.307 回答
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+";");

于 2013-11-02T06:48:32.203 回答