我正在嘗試檢查用戶輸入的值是否與我定義的值匹配。為此,我<form>使用方法創建了一個POST。因為我只是在嘗試代碼,所以我添加了一個參考同一value.php頁面的 action 屬性。然后我希望頁面echo的值是否與我匹配。我遇到了一個奇怪的問題,我在 Stack Overflow 上的另一篇文章中讀到過這個問題,但我仍然不太明白為什么會發生這種情況。
這是檔案<form>內容的value.php代碼:
<form action="value.php" method="POST">
<input type="text" name="fruit" placeholder="FRUIT HERE"><br>
<input type="text" name="vegetable" placeholder="VEGETABLE HERE">
<button type="submit">CHECK</button>
</form>
在value.php上面的同一個檔案中,<form>我有以下 PHP 代碼:
<?php
$db_fruit = 'apple';
$db_vegetable = 'tomato';
if (isset($_POST['fruit']) && isset($_POST['vegetable'])) {
$fruit= htmlentities($_POST['fruit']);
$vegetable = htmlentities($_POST['vegetable']);
if (!empty($fruit) && !empty($vegetable)) {
if ($fruit == $db_fruit && $vegetable == $db_vegetable) {
echo 'The values do match.';
} else {
echo 'The values do not match.';
}
}
}
?>
由于isset();PHP 代碼中的函式,我希望echo除非用戶單擊<button>with ,否則不會執行type="submit"。但是,如果實際上提供了錯誤的值,并且即使接受警告并單擊重繪 頁面echo 'The values do not match.';,代碼echo也不會消失。我怎樣才能使它不會出現在頁面重繪 并且頁面會出現“全新”?Confirm form resubmissionContinueecho
我還應該指出,我最好尋找一種不需要使用 JavaScript 的解決方案。
uj5u.com熱心網友回復:
它與您在此處發布的代碼完全相同,我合并了 2 個不同的部分,對于這種情況,您需要防止在重繪 時重新提交表單,因此我在腳本標簽之間添加了 javascript。此外,稍微改變了邏輯,在我看來,收集將在陣列中回顯的文本,并將它們回顯在一起是更好的方法,但它并沒有太大變化。您還可以通過包含腳本來嘗試最新版本。
<?php
$db_fruit = 'apple';
$db_vegetable = 'tomato';
$result = array();
if (isset($_POST['fruit']) && isset($_POST['vegetable'])) {
$fruit= htmlentities($_POST['fruit']);
$vegetable = htmlentities($_POST['vegetable']);
if (!empty($fruit) && !empty($vegetable)) {
if ($fruit == $db_fruit && $vegetable == $db_vegetable) {
$result[] = 'The values do match.';
} else {
$result[] = 'The values do not match.';
}
}
}
if (!empty($result)) {
foreach ($result as $val) {
echo "$val";
}
}
?>
<script> //this part will not allow form resubmit on refresh !
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
<form action="" method="POST"> //because php code is on same file action empty
<input type="text" name="fruit" placeholder="FRUIT HERE"><br>
<input type="text" name="vegetable" placeholder="VEGETABLE HERE">
<button type="submit">CHECK</button>
</form>
uj5u.com熱心網友回復:
沒有重新提交表單,回聲仍然出現?這很奇怪,也許您的瀏覽器仍在發送 POST 單擊繼續...
無論如何,您可以應用的一個技巧是使用會話控制變數。
就在表單之前,但在管理 POST 之后,您定義了一個會話變數,給它一個隨機值,例如:
$_SESSION['control'] = rand(100000, 999999);
并將該值作為隱藏輸入放入表單中:
<input type="hidden" name="control" value="<?php echo $_SESSION['control']; ?>" >
現在您可以檢查發送的控制元件是否與當前控制元件匹配,而不是檢查水果和蔬菜(如果需要,您仍然可以這樣做):
if (isset($_POST['control']) && isset($_SESSION['control']
&& $_POST['control'] == $_SESSION['control`]) {
當然,不要忘記在腳本開始時啟動會話:
session_start();
就這樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/345931.html
上一篇:GET輸入作為PHP陣列
