我正在使用這個 ajax 腳本來保留頁面上的所有資訊,即使在按下提交之后
<!DOCTYPE html>
<html>
<head>
<title>AJAX POST Submit</title>
<script>
function ajaxpost () {
// (A) GET FORM DATA
var form = document.getElementById("myForm");
var data = new FormData(form);
// (B) AJAX
var xhr = new XMLHttpRequest();
xhr.open("POST", "0-dummy.php");
// What to do when server responds
xhr.onload = function () { console.log(this.response); };
xhr.send(data);
// (C) PREVENT HTML FORM SUBMIT
return false;
}
</script>
</head>
<body>
<form id="myForm" onsubmit="return ajaxpost()">
Name: <input type="text" name="name" required/>
Email: <input type="text" name="email" required/>
<input type="submit" id = "hello"value="Go!"/>
</form>
</body>
我基本上想在幾分鐘后更新表單并將其發布到“dummy.php”,而無需按下提交按鈕并擦除頁面上的資料。
<script>
//var div = document.getElementById('myForm');
//var submitted = document.getElementById('hello');
function CountDown(duration, display) {
var timer = duration, minutes, seconds;
var interVal= setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" minutes : minutes;
seconds = seconds < 10 ? "0" seconds : seconds;
display.innerHTML ="<b>" minutes "m : " seconds "s" "</b>";
if (timer > 0) {
--timer;
}else{
clearInterval(interVal)
document.getElementById('myForm').submit();
}
},1000);
}
function SubmitFunction(){
//submitted.innerHTML="Time is up!";
document.getElementById('myForm').submit();
}
//CountDown(5,div);
</script>
</html>
我想要這種方式的原因是因為我正在嘗試制作一個 html 頁面,該頁面使用 php 每隔幾分鐘將復選框的值發布到文本檔案中。復選框的值決定了連接到從文本檔案收集所有資料的設備的電路。
uj5u.com熱心網友回復:
所以你需要的只是避免你寫的大部分內容,并堅持以下內容:
<input type="button" onclick="setInterval(ajaxpost,1000);" id = "hello"value="Go!"/>
這里的技巧首先將型別從 更改submit為button。
第一次點擊Go后會發生什么,它會保持每秒發送一次,并洗掉onsubmit="return ajaxpost()"
以下是我做的測驗:
<!DOCTYPE html>
<html>
<head>
<title>AJAX POST Submit</title>
<script>
function ajaxpost () {
// (A) GET FORM DATA
var form = document.getElementById("myForm");
var data = new FormData(form);
// (B) AJAX
var xhr = new XMLHttpRequest();
xhr.open("POST", "help.php");
// What to do when server responds
xhr.onload = function () { console.log(this.response); };
xhr.send(data);
}
</script>
</head>
<body>
<form id="myForm" >
Name: <input type="text" name="name" required/>
Email: <input type="text" name="email" required/>
<input type="button" onclick="setInterval(ajaxpost,1000);" id = "hello"value="Go!"/>
</form>
</body>
我的 hello.php 只是:
<?php
echo $_POST["name"]."". $_POST["email"];
希望能回答這個問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/503854.html
