我在使用ajax时遇到问题。如果我删除表单标签然后它工作正常,结果显示在同一页面上。但是使用表单标签,结果显示在不同的页面上,即直接连接到servlet但是我正在尝试使用表单标签完整地构建此项目并从ajax而不是表单操作提交它,这是我的代码
account_recovery.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="js/jquery-1.11.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#subm").click(function(){
var email = $('#inputEmail').val();
if(email.length >= 3){
$(".statusMessage").html("<img src='images/loading.gif'><font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "ForgotPasswordServlet",
data: "email="+ email,
success: function(msg){
$(".statusMessage").html(msg);
}
});
}
else{
$(".statusMessage").html("<font color=red>Email should be <b>3</b> character long.</font>");
}
});
});
</script>
</head>
<body>
<jsp:include page="header.jsp"/>
<br/>
<div class="container">
<div class="col-md-6">
<form class="form-horizontal" action ="ForgotPasswordServlet" method ="POST">
<h4 class="form-signin-header" style="margin-top: 75px;">Forgot your password?</h4>
<br/>Enter the email address that you usually sign in with and we'll help you recover your account.
<label for="inputUser" class="sr-only"><b>Email:</b></label>
<br/><input type="text" id="inputEmail" name="email" class="form-control" placeholder="Enter your email address" required autofocus>
<span class="statusMessage"></span>
<br/>
<button class="btn btn-md btn-primary btn-success" type="submit" id="subm"/>Submit</button>
<br/>For more help to find your email address or password, visit the <a href="#">Help page</a>
</form>
</div>
</div><!---end container--->
<jsp:include page="footer.jsp"/>
</body>
</html>
如果需要,可以提供servlet的代码
答案 0 :(得分:1)
您没有阻止表单提交。 而是试试这个。
<script type="text/javascript">
$(document).ready(function(){
$('form').on('submit',function(event){
event.preventDefault();
var email = $('#inputEmail').val();
if(email.length >= 3){
$(".statusMessage").html("<img src='images/loading.gif'><font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "ForgotPasswordServlet",
data: "email="+ email,
success: function(msg){
$(".statusMessage").html(msg);
}
});
}
else{
$(".statusMessage").html("<font color=red>Email should be <b>3</b> character long.</font>");
}
});
});
</script>