在作提交頁面的時候,總有一個需求是防止重複提交 html代碼以下html
<form action="../mockup/json/test.json" class="clearfix" onsubmit="return false"> <input type="hidden" name="service_id" id="" value="" /> <input type="hidden" name="product_id" id="" value="" /> <input type="hidden" name="instalment_amount" id="" value="" /> <input type="submit" name="" id="_pushBill" value="提交訂單" /> </form>
js代碼以下ajax
$('#_pushBill').on('click',function(){ var timer = null; var self = $(this); //節流函數是用來控制點擊頻次 clearTimeout(timer); timer = setTimeout(function(){ $.ajax({ type:"post", url:$('form').attr('action'), async:true, dataType: "json", data: $('form').serialize(), beforeSend: function () { //讓提交按鈕失效,以實現防止按鈕重複點擊 self.prop('disabled', 'disabled'); //給用戶提供友好狀態提示 self.prop('value', '正在提交'); }, success: function(res) { showTip($('#_tip'), res.msg); if (res.flag) { setTimeout(function() { location.href = res.url; }, 2000); } }, error: function() { showTip($('#_tip'), "請求服務異常,稍後再試"); }, complete: function () { //讓登錄按鈕從新有效 setTimeout(function(){ self.removeAttr('disabled') },3000); } }) },100) })