我想调用一个返回值的 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 + "'"; }>您不能在JSP的if语句中调用JavaScript函数,因为JSP在服务器端执行而JavaScript在客户端执行.
>单击单选按钮时必须触发事件,使用onclick事件可以调用函数corc().
>不要在JSP中编写scriptlet,因为scriptlet不应该在JSP中使用超过十年.学习JSP EL, JSTL,并使用servlet作为Java代码. How to avoid Java Code in JSP-Files?
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中提交表单时,您可以获得隐藏字段的值.
String tableName = request.getParameter(“tableValue”); // pass the name of hidden field i.e. tableValue
>您可以进一步传递此tableName以进行查询.
相关链接
> How to transfer data from JSP to servlet?
> forms in HTML