如何在JSP中访问JavaScript变量值?

1 jsp

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);
  %>
}
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 5

请记住,示例中的JavaScript在客户端,浏览器中运行; JSP代码正在服务器上运行.要访问服务器上的客户端数据,您必须将其从客户端发送到服务器,您不能像在示例中那样内联访问它.这通常通过提交表单或执行Ajax请求来完成.

例如,使用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... */
}
Run Code Online (Sandbox Code Playgroud)

或者使用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... */
}
Run Code Online (Sandbox Code Playgroud)

无论哪种方式,您的modifyRecord.jsp都会收到一个POST参数rec,可用于执行数据库操作(在小心防范SQL注入攻击之后).