2010-03-29 49 views
1
function modification() 
{ 

    alert(document.getElementById("record").value); 
    var rec=document.getElementById("record").value; 
    <% 
    Connection connect = DriverManager.getConnection("jdbc:odbc:DSN","scott","tiger"); 
    Statement stm=connect.createStatement(); 
    String record=""; // I want value of "rec" here. 

    ResultSet rstmt=stm.executeQuery("select * from "+record); 
    %> 
} 
+2

http://xkcd.com/327/ – simon 2010-03-29 07:04:35

+0

http://balusc.blogspot.com/2009/05/javajspjsf-and-javascript.html – BalusC 2010-03-29 12:08:52

回答

5

请记住,您示例中的JavaScript运行在浏览器中的客户端上; JSP代码运行在服务器上。要访问服务器上的客户端数据,必须将其从客户端发送到服务器,因此无法像在示例中那样以内联方式访问它。这通常通过提交表格或执行Ajax request完成。

例如,使用Prototype,您modification功能可能是这样的:

function modification() 
{ 
    var rec=document.getElementById("record").value; 
    new Ajax.Request("modifyRecord.jsp", { 
    parameters: {rec: rec}, 
    onFailure: showUpdateFailure 
    }); 
} 

function showUpdateFailure(response) { 
    /* ...code here to show that the update failed... */ 
} 

或者使用jQuery,它可能是这样的:

function modification() 
{ 
    var rec=document.getElementById("record").value; 
    $.ajax({ 
    url: 'modifyRecord.jsp', 
    data: {rec: rec}, 
    error: showUpdateFailure 
    }); 
} 

function showUpdateFailure(xhr, errmsg) { 
    /* ...code here to show that the update failed... */ 
} 

无论哪种方式,你会modifyRecord.jsp会收到一个POST参数rec它可以用来执行数据库操作(在仔细防御SQL injection attacks后)。