1

我正在用jsp和java开发一个测试系统

在客户端,我有以下代码:

        var xmlhttp = new getXmlHttpRequestObject(); //xmlhttp holds the ajax object


        function servletPost() {
            if(xmlhttp) { 
                //var txtname = document.getElementById("testForm");
                var form = $('#testForm');
                xmlhttp.open("POST","servlet/TestingController",true);
                xmlhttp.onreadystatechange = handleServletPost;
                xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xmlhttp.send(form.serialize()); 
            }
        }

        function handleServletPost() {
            //var qComplexity = document.getElementsByName("qComplexity")[0].value;  


            if (xmlhttp.readyState == 4) {
                if(xmlhttp.status == 200) {
                    var respText = xmlhttp.responseText;

                    document.getElementById("fullQuestion").innerHTML = respText;
                    // here i also should change the content of the answer options
                    // so i should get from servlet multiple variables
                    // which allows me to change div contents in my jsp like as respText.question or respText.answer[0]
                } else {
                    alert("Ajax calling error");
                }                    
           }
        }

在服务器端:(我的 Servlet)

public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
 .........................................................
 .........................................................

 PrintWriter out = res.getWriter();
 String complex = null;
        int categ_id = -1;
        String asked_by = null;
        String Qtext = null;
        int qid = -1;
        q_numb = 1;
        q_numb++;
        String sqlSelect = "SELECT * FROM questions WHERE complexity = '" + complexity 
                        + "'ORDER BY RANDOM() LIMIT 1;";

        ResultSet r = myConnection.runQuery( sqlSelect );
        session.setAttribute("member", tempMem);

        while (r.next()) {
            complex = r.getString(5);
            categ_id = r.getInt(4);
            asked_by = r.getString(3);
            Qtext = r.getString(2);
            qid = r.getInt(1);

            String sqlA = "select * from answers where question_id = '" + qid 
                                + "' ORDER by RANDOM();";

            ResultSet result = myConnection.runQuery( sqlA );
            session.setAttribute("member", tempMem); }

所以我需要发送 complex、Qtext、qid、categ_id 等值。是否有任何结构可以从 ajax 发送到 servlet,反之亦然?以及如何在客户端处理发送的数据?

提前致谢!!!!

4

1 回答 1

1

使用JSON。有无数免费的 Java JSON 编组器。JavaScript 原生支持 JSON。

于 2013-04-02T18:47:45.233 回答