我有以下文件:
view.jsp的
<@ page import=...
<bean:define id="mForm" name="myForm" type="MyForm"/>
<html:form action="MyFoo" method="post" styleId="myForm" enctype="multipart/form-data">
<html:hidden property="boo"/>
<input type="button" value="Press me" onclick="javascript:changeBoo()"/>
</html:form>
MyForm.java
class MyForm {
private boolean boo;
public void setBoo(boolean boo){
this.boo = boo;
}
public boolean getBoo(){
return this.boo;
}
}
MyFooAction.java
public class MyFooAction extends BaseAction {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward aForward = null;
String forward = "success";
try {
MyForm myForm = (MyForm) form;
String boo = (String)request.getParameter("boo");
if(boo.equals("true")){
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>DONE");
}
else {
//some code here
}
aForward = mapping.findForward(forward);
}
catch (Exception e) {
throw new Exception();
}
return aForward;
}
}
问题是如何在Javascript中实施changeBoo()
以更改boo
的值并使用正确的值MyFooAction
调用boo
?
答案 0 :(得分:3)
首先,将您的按钮更改为type="submit"
。这将负责为您提交表格。请注意changeBoo()
现在如何返回onclick属性的值。如果您的函数返回true
,则会提交表单。
此外,您需要在隐藏字段中添加id
属性,以便您可以从javascript轻松获取对它的引用:
<html:hidden property="boo" id="booId" />
<input type="submit" value="Press me" onclick="return changeBoo();"/>
然后,这只是创建javascript函数的问题:
function changeBoo(){
var boo = document.getElementById('booId');
boo.value = 'The new value';
return true;
}
答案 1 :(得分:1)
PS 在<html:form>...</html:form>
上,确保您有办法提交表单。这通常是通过添加<html:submit>
。
现在,回到你的问题,你的Javascript函数将是这样的(假设你在struts-config.xml上指定的ActionForm
名称是“myForm”)。 / p>
fumction changeBoo() {
var boo = document.myForm.boo;
if ("true" == boo.value.toLowerCase() || "yes" == boo.value.toLowerCase() || "1" == boo.value.toLowerCase()) {
boo.value = "false";
} else {
boo.value = "true";
}
}
请记住,Struts将布尔值转换为“true”或“false”,“yes”或“no”,“0”或“1”。