1> 定義標誌位:
點擊觸發請求後,標誌位爲false量;請求(或者包括請求後具體的業務流程處理)後,標誌位爲true量。通過標誌位來判斷用戶點擊是否具備應有的響應。
2> 卸載及重載綁定事件:
點擊觸發請求後,卸載點擊事件;請求(或者包括請求後具體的業務流程處理)後,重新載入綁定事件。
3> 替換(移除)按鈕DOM
點擊觸發請求後,將按鈕DOM對象替換掉(或者將之移除),自然而然此時不在具備點擊事件;請求(或者包括請求後具體的業務流程處理)後,給新的按鈕DOM定義點擊事件。
具體措施
一、表單提交
<form action="login.do" method="post"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="submit" οnclick="this.disabled=true; this.value='登錄中...'; this.form.submit();" value="登錄" /> </form>
二、ajax請求
(function ($) {
$('.J-login').click(function () {
var loginBtn = this;
//1.先進行表單驗證
//......
//2.讓提交按鈕失效,以實現防止按鈕重複點擊
$(loginBtn).attr('disabled', 'disabled');
//3.給用戶提供友好狀態提示
$(loginBtn).text('登錄中...');
//4.異步提交
$.ajax({
url: 'login.do',
data: $(this).closest('form[name="loginForm"]').serialize(),
type: 'post',
success: function(msg){
if (msg === 'ok') {
alert('登錄成功!');
//TODO 其他操作...
} else {
alert('登錄失敗,請重新登錄!');
//5.讓登陸按鈕重新有效
$(loginBtn).removeAttr('disabled');
}
}
});
});
})(jQuery);
或者:
(function ($) {
$('.J-login').click(function () {
var loginBtn = this;
//1.先進行表單驗證
//......
//2.異步提交
$.ajax({
url: 'login.do',
data: $(this).closest('form[name="loginForm"]').serialize(),
type: 'post',
beforeSend: function () {
//3.讓提交按鈕失效,以實現防止按鈕重複點擊
$(loginBtn).attr('disabled', 'disabled');
//4.給用戶提供友好狀態提示
$(loginBtn).text('登錄中...');
},
complete: function () {
//5.讓登陸按鈕重新有效
$(loginBtn).removeAttr('disabled');
},
success: function(msg){
if (msg === 'ok') {
alert('登錄成功!');
//TODO 其他操作...
} else {
alert('登錄失敗,請重新登錄!');
}
}
});
});
})(jQuery);
三、請求頻度(節流函數)
var timer = null;
$(input).keyup(function(){
var value = $(this).val();
clearTimeout(timer);
//如果鍵盤敲擊速度太快,小於100毫秒的話就不會向後臺發請求,但是最後總會進行一次請求的。
timer = setTimeout(function() {
//觸發請求
$.ajax({
url: 'typeahead.do',
type: 'get',
data: value,
success: function () {
//顯示匹配結果
//......
}
});
},100);
});
四、友好提示
//全站ajax加載提示
(function ($) {
var str = '<div class="ajax-status" style="display: none;">'
+ '<div class="ajax"><img src="' + publicPath + 'img/loading.gif" width="20" height="20" />數據加載中...</div>'
+'</div>';
var dom = $(str).prependTo('body');
$(document).ajaxStart(function(){
dom.stop(true,false).queue(function(){
$(this).show().dequeue();
});
});
$(document).ajaxStop(function(){
dom.queue(function(){
$(this).hide().dequeue();
});
});
})(jQuery);