如何从servlet发送多个变量作为对ajax帖子的响应?

时间:2013-04-02 18:42:10

标签: ajax jsp servlets

我正在开发一个使用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); }

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

提前致谢!!!!

1 个答案:

答案 0 :(得分:1)

使用JSON。有无数的免费Java JSON marshallers。 JSON本身也受JavaScript支持。