How can I access a JavaScript variable value in JSP?

前端 未结 1 467
礼貌的吻别
礼貌的吻别 2021-01-24 14:00
function modification()
{

  alert(document.getElementById(\"record\").value);
  var rec=document.getElementById(\"record\").value;
  <%
  Connection connect = Driver         


        
相关标签:
1条回答
  • 2021-01-24 14:34

    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 讨论(0)
提交回复
热议问题