【问题标题】:using ajax how to send parameter from 1 jsp page to another servlet使用ajax如何将参数从1个jsp页面发送到另一个servlet
【发布时间】:2011-12-19 07:46:08
【问题描述】:

我正在使用 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();
}
}

字符串 student 显示 null,即使数据库中有 studentid=student 的值。

【问题讨论】:

  • 您需要在服务器端代码中进行一些调试(或者至少告诉我们)——您看到了什么?

    + s +

    会生成吗?如果您看到

    null

    那么您有一行,但其中的值为 null....

标签: javascript jsp servlets


【解决方案1】:

由于您使用的是 HTTP-POST,因此您必须将参数放入发送方法中。

...
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);
...

【讨论】:

  • 我试过了,但它不起作用。它显示为 null。

    +s+

    。servlet 代码应该是什么:String student=request.getParameter("str") ;还好吗?
猜你喜欢
  • 2018-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-15
  • 1970-01-01
  • 1970-01-01
  • 2013-11-11
  • 1970-01-01
相关资源
最近更新 更多