无法将我的Ajax html与我的Java servlet连接起来

时间:2015-10-16 06:12:42

标签: javascript html ajax servlets

我已经在这方面工作了几个小时,在网上搜索有类似问题和潜在解决方案的人,我一直陷入困境。我正在尝试编写一个用javascript实现的支持Ajax的html表单,它将从文件扩展名为.java的servlet访问一些数据并将其保存在html页面的某个地方。我是编写servlet和编写Ajax的新手 - 我的html和javascript经验有限,所以我确定我错过了一些简单而明显的东西,但正如我所说,我已经在这工作了几个小时,我根本看不到它。非常感谢任何帮助或见解。提前致谢。 (以下代码:)

<html>
    <head>
    <title>Display Votes</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">        
        var xmlhttp;

        function getVotes() {
            if (window.XMLHttpRequest){
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }else{
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            var url = "DisplayMyVotesServlet?loginID=APP&password=pass";
            xmlhttp.open("GET", url, true);
            xmlhttp.onreadystatechange = callback;
            xmlhttp.send();
        }           
        function callback() {
            if (xmlhttp.readyState == 4) {
                alert(xmlhttp.readyState == 4);
                var theResult = xmlhttp.responseText.documentElement;
                alert(theResult);
                document.getElementById("results").innerHTML = theResult;              
            }
        }
    </script>
</head>
<body>
    <input type = "button" value="My Votes" onclick="getVotes()"/>
    <div id="results"></div>
</body>

和我的servlet:

@WebServlet(name = "DisplayMyVotesServlet", urlPatterns = {"/DisplayMyVotesServlet"})
public class DisplayMyVotesServlet extends HttpServlet {

    @Resource (name = "jdbc/HW2DB")
    private DataSource datasource;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        Connection connection = datasource.getConnection();
        String selectSQL = "select * from VOTES";
        PreparedStatement selectStatement = connection.prepareStatement(selectSQL);
        ResultSet resultSet = selectStatement.executeQuery();
        int numTotalVotes = 0;
        while(resultSet.next())
            numTotalVotes = numTotalVotes + resultSet.getInt("NUMVOTES");
        String result = "I have voted " + numTotalVotes + " times.";
        request.setAttribute("Result", result);
        resultSet.close();
        selectStatement.close();
        connection.close();
    }
}

0 个答案:

没有答案