js防止表單重複提交的兩種方法_javascript技巧

來源:互聯網
上載者:User
第一種:用flag標識,下面的代碼設定checkSubmitFlg標誌:
複製代碼 代碼如下:

<script language="”javascript”">

var checkSubmitFlg = false;

function checkSubmit(){

if(checkSubmitFlg ==true){ return false; //當表單被提交過一次後checkSubmitFlg將變為true,根據判斷將無法進行提交。

}

checkSubmitFlg ==true;

return true;

}

< /script >

< form name=”form1” method=”post” onsubmit=”return checkSubmit();”>

………..< /form>

第二種:在onsubmit事件中設定,在第一次提交後使提交按鈕失效,代碼如下:
複製代碼 代碼如下:

<form action=”about:blank” method=”post” onsubmit =”getElementById(‘submitInput').disabled=true;return true;” target=”_blank”>
<input type=”submit” id=”submitInput”/>
</form>
</body>
</html>
</script>

因為程式源碼跟WIN2000的註冊表有衝突,文章發出後會出現無效頁面,以致於論壇裡有很多無惡意的重複文章,後來想出了一個辦法,用JS避免重複提交,下面是部分源碼:
複製代碼 代碼如下:

<script Language='JavaScript'>
function formsubmit() {
Today = new Date();
var NowHour = Today.getHours();
var NowMinute = Today.getMinutes();
var NowSecond = Today.getSeconds();
var mysec = (NowHour*3600)+(NowMinute*60)+NowSecond;
if((mysec-document.formsubmitf.mypretime.value)>600)
//600隻是一個時間值,就是5分鐘內禁止重複提交,值隨你高興設
{
document.formsubmitf.mypretime.value=mysec;
}
else
{
alert(' 按一次就夠了,請勿重複提交!請耐心等待!謝謝合作!');
return false;
}
document.forms.formsubmitf.submit();
}
</script>

</HEAD>

<BODY BGCOLOR="#FFFFFF">
<form name=formsubmitf id ="the" method="post" action="XXX.asp">
<input type=hidden name='mypretime' value='0'> //這句不能少,用隱含變數傳遞一個時間初值

//這裡是你要提交的內容

<input type="button" value="寫好了" name="button1" class="4round" onclick='formsubmit()'> <font class="red">(請按一次,耐心等待!)</font> <input type="reset" value="重 寫" name="button2" class="4round">
</form>

用了這個代碼,論壇的重複文章明顯減少,不過有個缺點,就是重新整理一次,檢測就不起作用,好處就是利用JS檢測,不需要額外的許可權支援,至於效果如何,用不用就隨你們了,(最好前端跟後端都加上檢測)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.