1 回答

TA貢獻1807條經驗 獲得超9個贊
顯示這種消息通常稱為“閃現消息”:顯示出現過一次的消息,刷新后不再顯示。
您的問題來自瀏覽器的行為:如果頁面是從 POST 請求加載的,那么如果用戶點擊刷新按鈕,它將使用相同的 POST 參數發出新的 POST 請求
但你想要的是:如果頁面是從 POST 請求加載的,那么如果用戶點擊刷新按鈕,它將發出一個新的 GET 請求(當然:沒有任何 POST 參數)
可以使用session來實現,步驟如下:
用戶點擊一個按鈕(1 或 2)
POST 到自己 button1=Button1 或 button2=Button2
頁面處理請求(做郵件功能)
頁面重定向/刷新以顯示先前保存在會話變量中的新消息。
<?php
session_start();
if(array_key_exists('button1', $_POST)) {
button1();
}
else if(array_key_exists('button2', $_POST)) {
button2();
}
function button1() {
$_SESSION["msg"] = "mail";
echo "<script>window.location = window.location.pathname;</script>";
exit();
}
function button2() {
ini_set( 'display_errors', 1 );
error_reporting( E_ALL );
$from = "[email protected]";
$to = "[email protected]";
$subject = "Betreff";
$message = "Text";
$headers = "From:" . $from;
mail($to,$subject,$message, $headers);
$_SESSION["msg"] = "Test email sent";
echo "<script>window.location = window.location.pathname;</script>";
exit();
}
?>
<form method="POST">
<input type="submit" name="button1"
class="button" value="Button1" />
<input type="submit" name="button2"
class="button" value="Button2" />
</form>
<?php
if(!empty($_SESSION["msg"])){
echo $_SESSION["msg"];
$_SESSION["msg"] = null;
unset($_SESSION["msg"]);
}
?>
- 1 回答
- 0 關注
- 86 瀏覽
添加回答
舉報