2011-12-19 7 views
0

私はazaxを使用して動的にjspページを変更し、そのjspページからサーブレットにデータを送信したいとします。 JSPコード:ajaxを使用して1 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(); 
} 

サーブレットコード:

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(); 
} 
} 

ストリング学生値がstudentid =学生のためにデータベース内にあるにもかかわらずnull示します。

+0

あなたのサーバー側のコードにいくつかのデバッグを入れる必要があります(または少なくとも私たちに連絡してください) - あなたは何を見ていますか?

+ s +

が生成されますか?

null

が表示されている場合は、行がありますが、その値はnullです。 –

+0

nullを生成します –

答えて

0

HTTP-POSTを使用しているので、パラメータを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); 
... 
+0

これを試しましたが、それはうまく動作しません。

+ s +

サーブレットコードは何でしょうか?String student = request.getParameter( "str");これは問題ありませんか? –

+0

よく、私の問題を解決しました –

関連する問題