如何在jsp中使用javascript [英] how to use javascript in jsp
问题描述
我想调用一个返回值的javascript函数,然后将该值放在if语句中。 HTML中有两个单选按钮,javascript会检查单击哪一个。之后,JSP将其与客户或公司进行比较,并执行相应的SQL查询。
I want to call a javascript function that returns a value and then put that value in an if statement. There are two radio buttons in the HTML and the javascript checks to see which one is clicked. After that, the JSP compares it to either 'customers' or 'company' and does the appropriate SQL Query.
Javascript:
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是在客户端执行的。
You can not call JavaScript function in if statement of JSP, because JSP is executed at the server side and JavaScript is executed at client side.
单击单选按钮时必须触发事件,使用
onclick
事件可以调用函数corc()
。You have to trigger event when the one of the radio button is clicked, using
onclick
event you can call functioncorc()
.不要在JSP中编写scriptlet,因为scriptlet不应该在JSP中使用超过十年。学习JSP EL , JSTL ,并使用servlet作为Java代码。 如何避免JSP文件中的Java代码?
Do not write scriptlets in JSP, because scriptlets shouldn't be used in JSPs for more than a decade. Learn the JSP EL, the JSTL, and use servlet for the Java code. How to avoid Java Code in JSP-Files?
....... ........ //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
function并传递this.id
,参数this.id
用于传递单击的单选按钮的id
属性。onclick
event I assignedhandleClick
function and passedthis.id
, parameterthis.id
is used to pass theid
attribute of the clicked radio button.<script type="text/javascript"> function handleClick(clickedId) { if(clickedId == "customerId") document.getElementById('tableTextId').value = "customer"; else document.getElementById('tableTextId').value = "company"; } </script>
- 当您提交表单然后在servlet中,您可以获得值隐藏字段。
- 您可以进一步传递此
tableName
查询。 - You can further pass this
tableName
to query. - How to transfer data from JSP to servlet?
- forms in HTML
String tableName = request.getParameter(tableValue); //传递隐藏字段的名称,即tableValue
String tableName = request.getParameter("tableValue"); // pass the name of hidden field i.e. tableValue
这篇关于如何在jsp中使用javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!