1. 先看一下最终效果图:
当点击按钮提交时:
当点击取消时:
2. 问题描述
JSF的页面提交表单有两种方式
- 使用<h:commandButton/>
- 使用<h:commandLink/>
现在想在点击按钮或者链接时,先弹出一个提示弹窗,只有当点击确认
后才进行提交表单的操作
之前在用servlet或者ssm 、spring boot时,可以在一个自定义的函数中完成表单的提交,比如
// 其他业务逻辑
f.action = "后端url";
f.submt();
但是现在不能使用这种方式,因为JSF向后端发请求的方式不太一样(我目前是这么理解的)
JSF会把DOM组件的属性进行一些修改,加上一些自己的东西,比如这个input
的name属性
<input type="submit" name="j_idt6:j_idt7:0:j_idt37" value="选课"/>
除此以外他的请求url规则不太懂,因为他的form的action是这样子的:
<form id="j_idt4" name="j_idt4" method="post" action="/student_select_course_war_exploded/pages/login.xhtml" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="j_idt4" value="j_idt4">
学号:<input type="text" name="j_idt4:j_idt6" value="12019">
密码<input type="password" name="j_idt4:j_idt8" value=""><input type="submit" name="j_idt4:j_idt9" value="登录"><input type="hidden" name="javax.faces.ViewState" id="j_id1:javax.faces.ViewState:0" value="5828257949642758969:1121197389987952612" autocomplete="off">
</form>
也就是说:他指向的是当前页面
3. 问题解决
进过一波分析感觉不能对<h:commandButton/>
下手,应该另辟蹊径
于是乎,我在这个按钮旁边又添加了一个普通按钮,当我点击这个按钮的时候,他会出发一个自定义的js函数,在这个函数里进行弹窗提示,并进行表单提交
<h:commandButton action="#{cour.selectCourse(cour.id, student.id)}" style="display: none"/>
<button type="button" class="btn btn-primary btn-sm demo3" onclick="selectCourse(this)">选课</button>
弹窗函数如下:
function selectCourse(btn) {
swal({
title: "选课确认",
text: "是否确认选择当前课程?\n如想修改选课信息,请前往查看已选课程页面",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#1ab394",
confirmButtonText: "确认选课",
cancelButtonText: "取消选课",
closeOnCancel: false,
closeOnConfirm: true
}, function (isConfirm) {
if (isConfirm) {
$(btn).prev().click()
} else {
swal("已取消", "您取消了删除操作!", "error");
}
});
}
代码说明:
$(btn).prev().click()
表示获取当前元素的前一个兄弟元素
需要添加的js和css库文件
<link href="css/plugins/sweetalert/sweetalert.css" rel="stylesheet"/>
<link href="css/animate.css" rel="stylesheet"/>
<link href="css/style.css?v=4.1.0" rel="stylesheet"/>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/exist-other-course.js"></script>
<script type="text/javascript" src="js/plugins/sweetalert/sweetalert.min.js"></script>