【发布时间】:2011-01-31 22:11:21
【问题描述】:
我有一个登录表单,我正在尝试使用 ajax 处理。
乍一看还不错,
你点击登录按钮,
如果您的详细信息正确,则您已登录并重定向。
如果您的详细信息不正确,则会显示错误消息。
如果您等待错误消息消失并再次单击登录按钮,它就可以正常工作。
如果您不等待,它似乎会提交表单。
为什么会这样?
这里是代码
var timeout = null;
$(function() {
$('form').submit(function() {
var action = $(this).attr('action');
var type = $(this).attr('method');
$.ajax({
url: action,
type: type,
data: {
email: $('input[name=email]').val(),
pass: $('input[name=pass]').val()
},
success: function(data) {
switch (data.status) {
case false:
login_error(data.message);
return false;
break;
case true:
window.location = data.message;
return false;
break;
}
return false;
}
});
return false;
})
});
function login_error(message) {
$('form').effect('shake', { distance: 10, times: 3 }, 50);
if (timeout !== null) {
clearTimeout(timeout);
$('#login').stop().hide();
show_error(message);
} else {
show_error(message);
}
}
function show_error(message) {
$('#error').html(message)
.show("drop", {direction: 'left'}, 500);
timeout = setTimeout(function() {
$('#error').hide("drop", {direction: 'right'}, 500);
timeout = null;
}, 5000);
}
编辑
好的,所以它实际上并没有刷新页面,
某些东西正在将表单设置为 display:none;
我通过代码添加了一大堆console.log(),然后点击了两次登录,现在看起来像:
var timeout = null;
$(function() {
$('form').submit(function() {
console.log(1);
var action = $(this).attr('action');
console.log(2);
var type = $(this).attr('method');
console.log(3);
$.ajax({
url: action,
type: type,
data: {
email: $('input[name=email]').val(),
pass: $('input[name=pass]').val()
},
success: function(data) {
console.log(4);
switch (data.status) {
case false:
console.log(5);
login_error(data.message);
return false;
break;
case true:
console.log(6);
window.location = data.message;
return false;
break;
}
console.log(7);
return false;
}
});
console.log(8);
return false;
})
});
function login_error(message) {
console.log(9);
$('form').effect('shake', { distance: 10, times: 3 }, 50);
console.log(10);
if (timeout !== null) {
console.log(11);
clearTimeout(timeout);
$('#login').stop().hide();
console.log(12);
show_error(message);
console.log(13);
} else {
console.log(14);
show_error(message);
console.log(15);
}
}
function show_error(message) {
console.log(16);
$('#error').html(message)
.show("drop", {direction: 'left'}, 500);
console.log(17);
timeout = setTimeout(function() {
console.log(18);
$('#error').hide("drop", {direction: 'right'}, 500);
timeout = null;
}, 5000);
console.log(19);
}
输出为:
1
2
3
POST http://localhost/buzz/ajax/login 200 OK 30ms
8
4
5
9
10
14
16
17
19
15
第二次点击
1
2
3
POST http://localhost/buzz/ajax/login 200 OK 30ms
8
4
5
9
10
11
12
16
17
19
13
18
【问题讨论】:
-
一个简单的解决方案是使您的错误对话框模态化。然后用户必须在尝试再次登录之前将其关闭。另一种可能性是将错误消息直接放在网页上,而不是使用对话框。
-
虽然实用,但我个人认为模态对话框是对 ui 的犯罪(除了在某些情况下,例如画廊的灯箱);)
-
事实上,我同意你的看法。天哪,为什么我什至建议它? :) 也就是说,如果您要使用错误对话框,正确的方法是使其成为模态。所以对我来说,这是在模态对话框和根本没有对话框之间的选择。
标签: javascript ajax forms