使用ajax如何将参数从1个jsp页面发送到另一个servlet

时间:2011-12-19 07:46:08

标签: javascript jsp servlets

我正在使用 azax 动态更改jsp页面,我想将该jsp页面中的数据发送到servlet。 jsp代码:

<input type="submit" oninput="loadXMLDoc(this.value)" value="ok" name="ok">
    <div id="myDiv">  
        Insert Id:<input id="p1" type="text" name="edit1" value=""style="visibility:hidden" size="30"/>
    </div>
function loadXMLDoc(str){
    var xmlhttp;
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("POST","edit?q="+str,true);
xmlhttp.send();
}

servlet代码:

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter(); Connection conn=null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "studentdatabase";
    String driver = "com.mysql.jdbc.Driver"; 
    String userName = "root"; 
    String password = "1234";
    String student=request.getParameter("str");
    Statement stmt;out.println(student);
    try {
        Class.forName(driver).newInstance();
        conn = DriverManager.getConnection(url+dbName,userName,password);
        String query = "select name1,telephone,email,department from studentinfo where studentid='"+student+"";
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        while(rs.next()){
            String s = rs.getObject(1).toString();
            out.println("<p> " +s+ "</p>");
        }
        conn.close;
        //System.out.println("Disconnected from database");
    } catch (Exception e) {
    e.printStackTrace();
}
}

即使studentntid = student数据库中有值,String学生也会显示null

1 个答案:

答案 0 :(得分:0)

由于您使用的是HTTP-POST,因此您必须将params放入send方法。

...
var params = "q="+str;
xmlhttp.open("POST", url, true);

xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close"); 
xmlHttp.send(params);
...