AJAX - 无法接收Servlet响应

时间:2011-10-29 10:32:56

标签: ajax

我正在为我的学校项目第一次尝试AJAX。我在接收来自服务器的响应时遇到问题(响应'状态'0)。我已经浏览了建议列表中的类似问题并尝试过,但问题仍然存在。希望有人可以指出我的AJAX代码出错了。

这是我的jsp代码:

    <%@ page import="java.io.IOException"%>
    <%@ page import="java.sql.SQLException"%>
    <%@ page import="java.sql.Connection"%>
    <%@ page import="java.sql.ResultSet"%>
    <%@ page import="java.sql.Statement"%>
    <%@ page import="com.p6qgen.*"%>

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Generate Question</title>
    <link rel="stylesheet" type="text/css" href="style.css" />

    <script type="text/javascript" src="js/jquery-1.6.2.js"></script>
  </head>
  <body>
    <script language="javascript" type="text/javascript">
    <!-- 

    // Checking whether the browser support AJAX or not
    function ajaxFunction() {
        var ajaxReq;  // The variable to hold XMLHttpRequest object
        //alert("ajaxFunction()");
        try {
            // Chrome, Firefox, Opera, Safari
            ajaxReq = new XMLHttpRequest();
        } catch (e){
            // Internet Explorer Browsers
            try{
                ajaxReq = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxReq = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    // Something went wrong
                    alert("Your browser does not support AJAX!");
                    return false;
                }
            }
        }
        //alert("Ajax object created...");
        /*
         * Start of server response handling
         */
        ajaxReq.onreadystatechange = parseXml;

        // Parsing the xml document
        function parseXml() {
            if(ajaxReq.readyState == 4){
                alert("in parseXml");
                if(ajaxReq.status == 200) {
                    alert("Status OK!");
                    var numQs = ajaxReq.responseXML.getElementsByTagName("numqs")[0];
                    alert(numQs);
                    for(var i=0; i<numQs; i++) {
                        num = i+1;
                        var question = ajaxReq.responseXML.getElementsByTagName("question")[i];
                        setQuestion(num, question.childNodes[0].nodeValue);
                    }
                } else if(ajaxReq.status == 404) {
                    alert("Page Not Found");
                } else {
                    alert("Error: " + ajaxReq.status)
                }
            }
            /* Just for debugging
            else {
                switch(ajaxReq.readyState) {
                case 0: alert("Not Initialize"); break;
                case 1: alert("Connection Establish"); break;
                case 2: alert("Request received"); break;
                case 3: alert("Answer in Progress"); break;
                }
            } */
        }

        /*function setQuestion(num, question) {
             var qsTag = document.getElementById("question");

             var qBody = "<font size=\"4\"> Question " + num;
             qBody += "<p>" + question +"</p></font>";
             // if the messageBody element has been created simple replace it otherwise
             // append the new element
             if (qsTag.childNodes[0]) {
                 qsTag.replaceChild(qBody,  qsTag.childNodes[0]);
             } else {
                 qsTag.appendChild(qBody);
             }
        }*/
        /*
         * End of server response handling
         */

        // Extract selected values from dropdown lists and store in corresponding var
        alert("going to show...");
        var numT01 = document.getElementById('numT01').value;
        var numT02 = document.getElementById('numT02').value;
        var numT03 = document.getElementById('numT03').value;
        var numT04 = document.getElementById('numT04').value;
        var numT05 = document.getElementById('numT05').value;
        var numT06 = document.getElementById('numT06').value;
        var numT07 = document.getElementById('numT07').value;
        var numT08 = document.getElementById('numT08').value;
        // Prepare query string
        var queryStr = "?num1=" + numT01 + "&num2=" + numT02 + "&num3=" + numT03 +
                        "&num4=" + numT04 + "&num5=" + numT05 + "&num6=" + numT06 +
                        "&num7=" + numT07 + "&num8=" + numT08;
        alert("dbg#" + numT01);
        // Send request to server (server-side 'QGenerator')
        ajaxReq.open("GET", "QGenerator" + queryStr, true);
        //ajaxReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        //ajaxReq.setRequestHeader("Content-length", queryStr.length);
        //ajaxReq.setRequestHeader("Connection", "close");
        ajaxReq.send(null);
    }




    //-->
    </script>



    <h1 align="center">Percentage Question</h1>
    <br>
    <form name="qtype">
        <table width="800" cellspacing="5" align="center">
            <tr>
                <td  width="200" align="right" valign="middle">
                    <input type="image" src="Pix/qt1.jpg" width="96" height="30" name="typ1">
                </td >
                <td align="center" valign="middle">
                    <font size="4">
                        No of Questions to generate:&nbsp;&nbsp;
                        <select id="numT01">
                            <option value="0" selected="selected">0</option>
                            <option value="5">5</option>
                            <option value="10">10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                        </select>
                    </font>
                </td>
            </tr>
            <tr><td></td></tr>
            <tr>
                <td  width="200" align="right" valign="middle">
                    <input type="image" src="Pix/qt2.jpg" width="96" height="30" name="typ2">
                </td >
                <td align="center" valign="middle">
                    <font size="4">
                        No of Questions to generate:&nbsp;&nbsp;
                        <select id="numT02">
                            <option value="0" selected="selected">0</option>
                            <option value="5">5</option>
                            <option value="10">10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                        </select>
                    </font>
                </td>
            </tr>
            <tr><td></td></tr>
            <tr>
                <td  width="200" align="right" valign="middle">
                    <input type="image" src="Pix/qt3.jpg" width="96" height="30" name="typ3">
                </td >
                <td align="center" valign="middle">
                    <font size="4">
                        No of Questions to generate:&nbsp;&nbsp;
                        <select id="numT03">
                            <option value="0" selected="selected">0</option>
                            <option value="5">5</option>
                            <option value="10">10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                        </select>
                    </font>
                </td>
            </tr>
            <tr><td></td></tr>
            <tr>
                <td  width="200" align="right" valign="middle">
                    <input type="image" src="Pix/qt4.jpg" width="96" height="30" name="typ4">
                </td >
                <td align="center" valign="middle">
                    <font size="4">
                        No of Questions to generate:&nbsp;&nbsp;
                        <select id="numT04">
                            <option value="0" selected="selected">0</option>
                            <option value="5">5</option>
                            <option value="10">10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                        </select>
                    </font>
                </td>
            </tr>
            <tr><td></td></tr>
            <tr>
                <td  width="200" align="right" valign="middle">
                    <input type="image" src="Pix/qt5.jpg" width="96" height="30" name="typ5">
                </td >
                <td align="center" valign="middle">
                    <font size="4">
                        No of Questions to generate:&nbsp;&nbsp;
                        <select id="numT05">
                            <option value="0" selected="selected">0</option>
                            <option value="5">5</option>
                            <option value="10">10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                        </select>
                    </font>
                </td>
            </tr>
            <tr><td></td></tr>
            <tr>
                <td  width="200" align="right" valign="middle">
                    <input type="image" src="Pix/qt6.jpg" width="96" height="30" name="typ6">
                </td >
                <td align="center" valign="middle">
                    <font size="4">
                        No of Questions to generate:&nbsp;&nbsp;
                        <select id="numT06">
                            <option value="0" selected="selected">0</option>
                            <option value="5">5</option>
                            <option value="10">10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                        </select>
                    </font>
                </td>
            </tr>
            <tr><td></td></tr>
            <tr>
                <td  width="200" align="right" valign="middle">
                    <input type="image" src="Pix/qt7.jpg" width="96" height="30" name="typ7">
                </td >
                <td align="center" valign="middle">
                    <font size="4">
                        No of Questions to generate:&nbsp;&nbsp;
                        <select id="numT07">
                            <option value="0" selected="selected">0</option>
                            <option value="5">5</option>
                            <option value="10">10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                        </select>
                    </font>
                </td>
            </tr>
            <tr><td></td></tr>
            <tr>
                <td  width="200" align="right" valign="middle">
                    <input type="image" src="Pix/qt8.jpg" width="96" height="30" name="typ8">
                </td >
                <td align="center" valign="middle">
                    <font size="4">
                        No of Questions to generate:&nbsp;&nbsp;
                        <select id="numT08">
                            <option value="0" selected="selected">0</option>
                            <option value="5">5</option>
                            <option value="10">10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                        </select>
                    </font>
                </td>
            </tr>
        </table>
        <br><br>
        <table align="center">
                <tr>
                    <td align="center" valign="middle">
                    <font size="4">
                        No of Questions to generate per page:&nbsp;&nbsp;
                        <select id="numQs_page">
                            <option value="5">5</option>
                            <option value="10">10</option>
                            <option value="20">20</option>
                        </select>
                    </font>
                </td>
                </tr>
                <tr><td></td></tr>
                <tr><td></td></tr>
                <tr>
                    <td align="center" valign="middle">
                        <button onclick="ajaxFunction()">
                            <img src="Pix/genQs.jpg" width= "252" height="50" />
                        </button>
                    </td>
                </tr>
        </table>
    </form>
    <div id="question"></div>
</body>

这是我的servlet代码:

    package com.p6qgen;

    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    //import org.apache.velocity.runtime.log.Log;

    /**
    * Servlet implementation class QGenerator
    */
    @WebServlet("/QGenerator")
    public class QGenerator extends HttpServlet {
private static final long serialVersionUID = 1L;

DBAccess dbAccess;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

//int num1, num2, num3, num4, num5, num6, num7, num8, total_qs;

/**
 * @see HttpServlet#HttpServlet()
 */
public QGenerator() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
    response.setContentType("text/xml");
    response.setHeader("Access-Control-Allow-Origin", "*");

    try {
        dbAccess = new DBAccess();
        conn = dbAccess.getConnection(); 
        stmt = conn.createStatement();            

        dbAccess.clearTable(conn, "T_Temp");
        dbAccess.clearTable(conn, "T_Question");
        //int num1 = 5;
        int num1 = Integer.parseInt(request.getParameter("num1"));
        int num2 = Integer.parseInt(request.getParameter("num2"));
        int num3 = Integer.parseInt(request.getParameter("num3"));
        int num4 = Integer.parseInt(request.getParameter("num4"));
        int num5 = Integer.parseInt(request.getParameter("num5"));
        int num6 = Integer.parseInt(request.getParameter("num6"));
        int num7 = Integer.parseInt(request.getParameter("num7"));
        int num8 = Integer.parseInt(request.getParameter("num8"));
        int total_qs = num1+num2+num3+num4+num5+num6+num7+num8;
        System.out.println(total_qs);
        System.out.println("num1: " + num1);
        int tbl_cnt = 0; // to count the solution tables created
        // Generating the question
        do {
            if(num1!=0) {
                T_Q01 q01 = new T_Q01();
                q01.generateQuestion();
                tbl_cnt++;
                String tbl_name = "T_S" + tbl_cnt;
                dbAccess.dropTable(conn, tbl_name); // delete table if existed
                dbAccess.createTable(conn, tbl_name); // created a new table
                q01.generateSol();
                num1--;
                total_qs--;
            }
            if(num2!=0) {
                T_Q02 q02 = new T_Q02();
                q02.generateQuestion();
                tbl_cnt++;
                String tbl_name = "T_S" + tbl_cnt;
                dbAccess.dropTable(conn, tbl_name); // delete table if existed
                dbAccess.createTable(conn, tbl_name); // created a new table
                q02.generateSol();
                num2--;
                total_qs--;
            }
            if(num3!=0) {
                T_Q03 q03 = new T_Q03();
                q03.generateQuestion();
                tbl_cnt++;
                String tbl_name = "T_S" + tbl_cnt;
                dbAccess.dropTable(conn, tbl_name); // delete table if existed
                dbAccess.createTable(conn, tbl_name); // created a new table
                q03.generateSol();
                num3--;
                total_qs--;
            }
            if(num4!=0) {
                T_Q04 q04 = new T_Q04();
                q04.generateQuestion();
                tbl_cnt++;
                String tbl_name = "T_S" + tbl_cnt;
                dbAccess.dropTable(conn, tbl_name); // delete table if existed
                dbAccess.createTable(conn, tbl_name); // created a new table
                q04.generateSol();
                num4--;
                total_qs--;
            }
            if(num5!=0) {
                T_Q05 q05 = new T_Q05();
                q05.generateQuestion();
                tbl_cnt++;
                String tbl_name = "T_S" + tbl_cnt;
                dbAccess.dropTable(conn, tbl_name); // delete table if existed
                dbAccess.createTable(conn, tbl_name); // created a new table
                q05.generateSol();
                num5--;
                total_qs--;
            }
            if(num6!=0) {
                T_Q06 q06 = new T_Q06();
                q06.generateQuestion();
                tbl_cnt++;
                String tbl_name = "T_S" + tbl_cnt;
                dbAccess.dropTable(conn, tbl_name); // delete table if existed
                dbAccess.createTable(conn, tbl_name); // created a new table
                q06.generateSol();
                num6--;
                total_qs--;
            }
            if(num7!=0) {
                T_Q07 q07 = new T_Q07();
                q07.generateQuestion();
                tbl_cnt++;
                String tbl_name = "T_S" + tbl_cnt;
                dbAccess.dropTable(conn, tbl_name); // delete table if existed
                dbAccess.createTable(conn, tbl_name); // created a new table
                q07.generateSol();
                num7--;
                total_qs--;
            }
            if(num8!=0) {
                T_Q08 q08 = new T_Q08();
                q08.generateQuestion();
                tbl_cnt++;
                String tbl_name = "T_S" + tbl_cnt;
                dbAccess.dropTable(conn, tbl_name); // delete table if existed
                dbAccess.createTable(conn, tbl_name); // created a new table
                q08.generateSol();
                num8--;
                total_qs--;
            }
        } while (total_qs > 0);

        // Counting total number of questions in T_Question table
        int row = dbAccess.countRow(conn, "Q_ID", "T_Question");

        response.getOutputStream().println("<?xml version=\"1.0\"?>");
        response.getOutputStream().println("<qpage>");
        response.getOutputStream().println("<numqs>");
        response.getOutputStream().println(row);
        response.getOutputStream().println("</numqs>");
        for(int i=0; i<row; i++) {
            int q_id = i+1;
            response.getOutputStream().println("<number>");
            response.getOutputStream().println(q_id + ".");
            response.getOutputStream().println("</number>");
            response.getOutputStream().println("<question>");
            String q_val = dbAccess.selectValue(conn, "Q_Val", "T_Question", "Q_ID", q_id);
            response.getOutputStream().println(q_val);
            response.getOutputStream().println("</question>");
        }
        response.getOutputStream().println("</qpage>");

        response.getOutputStream().flush();
        response.getOutputStream().close();

        stmt.close();
        conn.close(); 
    } catch(SQLException e) {
        System.err.println("-----SQLException-----");
        System.err.println("doGet Error: " + e.getSQLState());
    }

}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {


}

}

很抱歉发布了很长的代码,但我认为这可能会提供一个很好的信息来分析我的问题。

正如'BalusC'建议在'Servlet响应AJAX请求是空的'帖子中,我已经尝试包括:

    response.setHeader("Access-Control-Allow-Origin", "*");

但这仍然无法解决问题。 请咨询。

1 个答案:

答案 0 :(得分:0)

看起来this文章适合您的问题。您必须取消&#34;提交&#34;的默认行为。按钮。 button代码有一个属性type,即&#34;提交&#34;如果没有定义。所以你有两个选择:

  1. 将您的按钮更改为<button type="button" onclick="...">...</button>
  2. return false;
  3. 之后添加ajaxReq.send(null);

    您的parseXml - 函数也有错误。 getElementsByTagName(...)返回包含所有numqs个节点的NodeList。因此numQs的值将是一个xml节点,因此for循环的条件将失败。在for循环中使用它之前,您必须解析nodeValue个numQs。

    var numQs = parseInt(ajaxReq.responseXML.getElementsByTagName("numqs")[0].nodeValue, 10);
    for (var i = 0; i < numQs; i++) {
        ...
    }