AJAX输出为HTML表

时间:2011-05-15 20:49:53

标签: java javascript sql html ajax

是否可以将AJAX输出转换为html而不是纯文本?

我有一个从SQL数据库中提取类结果的文件。数据库连接工作,它打印,但它不是打印我想要的表格式,而是简单地将表格元素打印为页面上的文本。

public class hw11
{
    int crn;
    String output = "temp";

    public String getOfferings(int crn)
    {
        this.crn = crn;     

        //DB Connection
        String url = "jdbc:odbc:registrar";
        Connection con;
        PreparedStatement stmt;

        String query;
        query = "SELECT * FROM offerings WHERE crn = " + crn +";";

        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        }
        catch(java.lang.ClassNotFoundException e)
        {
            System.err.print("ClassNotFoundException: ");
            System.err.println(e.getMessage());
        }

        try
        {
            con = DriverManager.getConnection(url, "", "");
            stmt = con.prepareStatement(query);
            ResultSet rs = stmt.executeQuery();   

            output = "<table border='1'><tr>";
            output+= "<th>CRN</th><th>Course</th><th>Section</th><th>Dates</th><th>Times</th><th>Instructor</th><th>Room</th><th>Max Enrolled</th><th>Current Enrolled</th></tr>";

            while (rs.next())
            {
                String course = rs.getString("COURSE");
                String section = rs.getString("SECTION");
                String dates = rs.getString("DATES");
                String times = rs.getString("TIMES");
                String instructor = rs.getString("INSTRUCTOR");
                String room = rs.getString("ROOM");
                int enrollmax = rs.getInt("ENROLLMAX");
                int enrollcur = rs.getInt("ENROLLCURRENT");

                output += "<tr>";
                output += "<td>"+crn+"</td><td>";
                output += "<td>"+course+"</td><td>";
                output += "<td>"+section+"</td><td>";
                output += "<td>"+dates+"</td><td>";
                output += "<td>"+times+"</td><td>";
                output += "<td>"+instructor+"</td><td>";
                output += "<td>"+room+"</td><td>";
                output += "<td>"+enrollmax+"</td><td>";
                output += "<td>"+enrollcur+"</td><td>";
                output += "</tr>";
            }

            output += "</table>";

            stmt.close();
            con.close();
        }

        catch (SQLException ex)
        {
            System.err.println("SQLException: " + ex.getMessage());
        }     


        //Output
        return output;
    }

}

HTML页面:

<p>

Get Course Offerings
<br/><br/>

Course CRN: <input type="text" id="theCrn"/>
<input value="Send" type="button" onclick="update()"/>

<br/>Reply:<br/>
<span id="theReply"></span>

</p>

1 个答案:

答案 0 :(得分:0)

是的,您可以返回任何内容以响应ajax调用。

请确保将其正确附加到页面上。