如何在JSP中访问JavaScript变量值? [英] How can I access a JavaScript variable value in JSP?

查看:56
本文介绍了如何在JSP中访问JavaScript变量值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

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

Remember that the JavaScript in your example is running on the client, in the browser; the JSP code is running on the server. To access client-side data on the server, you have to send it from the client to the server, you can't access it inline as in your example. This is usually done by submitting a form or doing an Ajax request.

例如,使用原型,您的modification函数可能如下所示:

For instance, using Prototype, your modification function might look like this:

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 ,它看起来可能像这样:

Or using jQuery, it might look like this:

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,该参数可用于执行数据库操作(在小心防御

Either way, your modifyRecord.jsp would receive a POST parameter rec which it could use to perform a database operation (after being careful to defend against SQL injection attacks).

这篇关于如何在JSP中访问JavaScript变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆