我正在使用Spring Framework MVC,我正在尝试使我的登录表单工作,但我真的是ajax的初学者。
这是我的index.jsp代码。
<!-- The Modal -->
<div id="modal1" class="modal2">
<span onclick="document.getElementById('modal1').style.display = 'none'" class="close" title="Close Modal">×</span>
<!-- Modal Content -->
<form:form id="login-form" method="POST" commandName="users" class="modal-content2 animate">
<div class="imgcontainer">
<img src="<c:url value=" /public/images/rsz_default-user.png "/>" alt="Avatar2" class="avatar">
</div>
<div class="container">
<p>
<label id="Correo"><b>Correo</b></label>
<input name="correo" id="correo" class="form-control" />
</p>
<p>
<label><b>Password</b></label>
<input type="password" name="password" id="password" class="form-control" />
</p>
<button type="submit"onclick="submitForm();"class="cyan">Enviar</button>
<button type="button" onclick="document.getElementById('modal1').style.display = 'none'" class="red">Cancel</button>
<span class="psw">Olvidaste tu <a href="#">Contraseña?</a></span>
</div>
</form:form>
</div>
这是我的LoginController:
@RequestMapping(value = "/index.htm", method = RequestMethod.POST)
public @ResponseBody String login(@ModelAttribute("users") Users u,BindingResult result) {
String returnText;
this.userValidations.validate(u, result);
Users user = checkUser(u.getCorreo(), u.getPassword());
if ((u.getCorreo().equals(user.getCorreo())) && (u.getPassword().equals(user.getPassword()))) {
returnText = "¡Bienvenid@ " + user.getNombre() + "!";
} else {
returnText = "Usuario incorrecto";
}
return returnText;
}
这是我的ajax函数,如果登录成功,则提交模态表单。
function submitForm(){
$('#login-form').on('submit', function (e) {
e.preventDefault();
var form = $(this);
alert("Estoy aca");
$.ajax('/index.htm', {
type: 'POST',
data: form.serialize(),
success: function (result) {
alert("Estoy aca");
Materialize.toast(result);
}
});
});
}
我的问题是,当我正确填写表单时,提交按预期工作,但如果我将错误的数据放入表单中,我不知道如何在不刷新或重定向页面的情况下将错误捕获到模态中。
答案 0 :(得分:0)
您的代码错误,为什么绑定到onclick事件中的提交事件。这是没有必要的,因为你已经绑定到onclick事件,并且你以编程方式执行ajax调用......
现在问你的实际问题,如果你在任何eventhadler函数中返回 false ,事件就会被取消。
一种简单的方法是制作验证器javascript函数,如果验证器不满意则返回false。
function isEverythingValid(){
var isFormValid = true;
//Validate all your form here
//for example:
if(document.getElementById('someId').value == ""){
isFormValid = isFormValid && false;
}
return isFormValid ;
}
function submitForm(){
if(isEverythingValid()){
$.ajax('/index.htm', {
type: 'POST',
data: form.serialize(),
success: function (result) {
alert("Estoy aca");
Materialize.toast(result);
}
});
}
else{
return false;
}