小编典典

如何在jsp中使用javascript

jsp

我想调用返回值的javascript函数,然后将该值放入if语句中。HTML中有两个单选按钮,javascript会检查单击哪个按钮。之后,JSP将其与“客户”或“公司”进行比较,并执行适当的SQL查询。

Javascript:

 function corc{
    var value;

    if(document.getElementById('cust').checked){
           value='customer';
            return value;
    }else if(document.getElmentById('comp').checked){
           value='company';
           return value;
    }
 }

JSP:

if(%>corc();<%.equals("customer")){
             String sqlqueryCommand = "SELECT * from customer where login='" + v1 + "' and password='" + v2     + "'";
}else if (%>corc();<%.equals("company")){
             String sqlqueryCommand = "SELECT * from company where login='" + v1 + "' and password='" + v2     + "'";
}

阅读 905

收藏
2020-06-08

共1个答案

小编典典

  • 您不能在JSP的if语句中调用JavaScript函数,因为JSP在服务器端执行,而JavaScript在客户端执行。

  • 单击单选按钮之一时必须触发事件,使用onclick事件可以调用function corc()

  • 不要在JSP中编写scriptlet,因为scriptlet在JSP中不应使用超过十年。学习JSPEL和JSTL,并将servlet用于Java代码。

JSP代码:

.......
........
//use <form> to submit values to servlet

 <input type="radio" name="radio1" onclick="handleClick(this.id);" id="customerId" />
 <input type="radio" name="radio1" onclick="handleClick(this.id);" id="companyId" />
......
.......
//use hidden field to assign table value i.e. "customer" or "company".
 <input type="hidden" name="tableValue" id="tableTextId" />  
//</form> closing form tag

onclick事件我分配了handleClick函数并传递了this.id参数this.id,用于传递id单击的单选按钮的属性。

JavaScript代码:

<script type="text/javascript">
  function handleClick(clickedId)
  {
     if(clickedId == "customerId")
       document.getElementById('tableTextId').value = "customer";
     else
       document.getElementById('tableTextId').value = "company";
  }
</script>
  • 当您提交表单然后在servlet中时,您可以获得隐藏字段的值。

字符串tableName = request.getParameter(“ tableValue”); //传递隐藏字段的名称,即tableValue

  • 您可以进一步将其传递tableName给查询。
2020-06-08