[英]How To Make 'Submit' Button Refresh Page?
在我的網站上,我有一個“聯系我們”表格。
當前,我正在使用php表單將已填寫的信息發送到我的電子郵件中。
我希望一旦有人單擊“提交”,就會出現回顯消息,但它會轉到帶有該消息的另一個頁面。
我只想刷新頁面。
這是PHP代碼:
<?php
//echo $emailBody;
sendEmail();
function sendEmail(){
global $emailBody, $name, $from, $fromName, $templateFile, $to, $subject;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "Reply-To: ". $from . "\r\n";
$headers .= "From: ". $from . "\r\n";
$headers .= "Return-Path: ".$from;
if (!mail($to, $subject, $emailBody, $headers)) {
} else {
echo "Your Message has been sent!we will contact back you in a short moment!";
}
}
?>
PHP將始終向您發送一個新頁面,因為它是服務器端語言。 為了在用戶單擊按鈕然后將結果顯示給用戶時執行此代碼,必須將請求發送到服務器,執行,然后再發送回用戶。 像您所請求的那樣“刷新”頁面的唯一方法是使用客戶端語言(例如javascript)。
就像這樣:當用戶單擊提交按鈕時,他們正在請求PHP處理該請求。 這只能在服務器上進行。 因為請求是從用戶到服務器再到用戶,所以您將始終獲得一個新頁面。
需要更多代碼,但通常在執行類似操作時,您需要將表單提交回iself,並在php的頂部,進行一些isset(-form variable-)檢查,如果已填寫,則可以從那里輸入要處理的功能,然后向用戶回顯一條消息,指示成功/失敗。
我會用:
<script type="text/javascript">
setTimeout(function(){location.reload();},1000);
</script>
<noscript>
<meta http-equiv="refresh" content="1" />
</noscript>
您還可以使用標頭來指定它(meta-refresh僅模擬此標頭):
header('Refresh: 1');
給用戶留言,例如:
<div>If this page doesn't automatically refresh in one second <a href="whatever">click here</a>.</div>
改變你的action
<form action="This is where your webpage goes" method="POST">
因此,這會將您的頁面發送給Google:
<form action="http://google.com" method="POST">
如果刪除該操作,它將重新加載當前頁面,如下所示:
<form method="POST">
只需將您的php與<form>
放在同一頁面即可。
像下面
<?php
if($_POST['submit'] == 'send'){
sendEmail();
function sendEmail(){
global $emailBody, $name, $from, $fromName, $templateFile, $to, $subject;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "Reply-To: ". $from . "\r\n";
$headers .= "From: ". $from . "\r\n";
$headers .= "Return-Path: ".$from;
if (!mail($to, $subject, $emailBody, $headers)) {
} else {
echo "Your Message has been sent!we will contact back you in a short moment!";
}
}
}
//For that to work your button needs to be like this
?>
<form method="POST">
<!-- other fields here -->
<input type="submit" name="submit" value="send" />
</form>
在回顯之前,您可以使用要顯示在此處的消息重定向到源頁面。
例如
if (!mail($to, $subject, $emailBody, $headers)) {
} else {
$myMsg="Your Message has been sent!we will contact back you in a short moment!";
header('location: yourpage');
}
在您的頁面中,您可以查看是否有類似這樣的消息
if(isset($myMsg))
{
echo $myMsg; // in the place & style that you want
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.