[计时器过期时未提交表格。这是我的代码。
<!DOCTYPE html>
<html>
<head>
<title>
How to call PHP function
on the click of a Button ?
</title>
</head>
<body style="text-align:center;">
<h4>
How to call PHP function
on the click of a Button ?
</h4>
<form action="test1.php" method="post">
<input type="submit" name="button1" id="button1"
class="button" value="Button" />
</form>
<div id="timer"></div>
<script type='text/javascript'>
var start = new Date();
var x=setInterval(function() {
// check time elapsed given target time of 10 mins from now
var timeLeft = (6000 - (new Date() - start))/1000;
// update timer
document.getElementById('timer').innerHTML = Math.floor(timeLeft/60) + ":" + Math.floor(timeLeft%60);
// check if timer has elapsed, and submit form
if (timeLeft < 0) {
document.forms["button1"].submit();
}
}, 1000);
</script>
</body>
</html>
您正在尝试“提交”按钮,而不是表单。您可以单击一个按钮,但不能提交一个按钮。提交事件是针对表单的。
(注意:打开浏览器的调试控制台,并观察到document.forms["button1"]
返回undefined
,因为没有带有该标识符的form。在某些地方无法正常工作时,请始终在控制台中检查错误。]
给表单一个标识符,并更新该行代码以由该标识符获取它:
var start = new Date();
var x=setInterval(function() {
// check time elapsed given target time of 10 mins from now
var timeLeft = (6000 - (new Date() - start))/1000;
// update timer
document.getElementById('timer').innerHTML = Math.floor(timeLeft/60) + ":" + Math.floor(timeLeft%60);
// check if timer has elapsed, and submit form
if (timeLeft < 0) {
document.forms["form1"].submit();
}
}, 1000);
<form action="test1.php" method="post" id="form1">
<input type="submit" name="button1" id="button1" class="button" value="Button" />
</form>
<div id="timer"></div>