开发者

How can I access a JavaScript variable value in JSP?

function modification()
{

  alert(document.getElementById("record").开发者_C百科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);
  %>
}


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.

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... */
}

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... */
}

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜