表單提交後不刷新頁面,最常見的做法是 AJAX。但其實還有另一種思路——利用隱藏的 iframe 作為提交目標,讓表單在幕後完成傳送,頁面本身完全不跳動。以下分享兩種實作方式。
關鍵是將表單的 target 指向一個隱藏的 iframe,資料便會送到該框架中處理,主頁面維持不變:
<iframe name="formsubmit" style="display:none;"></iframe>
<!-- 將表單提交導向隱藏的 iframe -->
<form action="form.php" method="POST" name="formphp" target="formsubmit">
<label for="uname">用戶名:</label>
<input type="text" name="uname" id="uname" />
<label for="pwd">密 碼:</label>
<input type="password" name="pwd" id="pwd" />
<input type="submit" value="登錄" />
</form>
後端 PHP 收到資料後,可直接輸出提示腳本,訊息便會在使用者眼前跳出:
<?php
// 非空驗證
if (empty($_POST['uname']) || empty($_POST['pwd'])) {
echo '<script>alert("用戶名或密碼為空!");</script>';
exit;
}
// 驗證密碼
if ($_POST['uname'] != 'jack' || $_POST['pwd'] != '123456') {
echo '<script>alert("用戶名或密碼不正確!");</script>';
exit;
} else {
echo '<script>alert("登錄成功!");</script>';
exit;
}
?>
若想取得後端回傳的資料並做進一步處理,可以監聽 iframe 的 onload 事件,讀取其內容後解析:
<iframe name="myiframe" style="display:none;" onload="iframeLoad(this);"></iframe>
<form action="form.php" target="myiframe" method="POST">
用戶名:<input type="text" name="username" /><br/>
密 碼:<input type="password" name="userpwd" /><br/>
<input type="submit" value="登錄" />
</form>
<script>
function iframeLoad(iframe){
var doc = iframe.contentWindow.document;
var html = doc.body.innerHTML;
if (html != '') {
var obj = eval("(" + html + ")"); // 將回傳字串轉為物件
alert(obj.msg);
if (obj.status >= 1) {
window.location.href = "https://www.baidu.com";
}
}
}
</script>
對應的 PHP 只要輸出 JSON 格式的狀態與訊息即可:
<?php
$msg = array('status' => 0, 'msg' => '');
$name = $_POST['username'];
$pwd = $_POST['userpwd'];
if ($name != 'jack') {
$msg['msg'] = '該用戶未注冊!';
} else if ($pwd != 'jack2014') {
$msg['msg'] = '輸入的密碼錯誤!';
} else {
$msg['msg'] = '登錄成功!';
$msg['status'] = 1;
}
echo json_encode($msg);
?>
以上兩種以 iframe 實現無刷新表單提交的做法,各有適用場景:前者簡單直接,後者則能靈活取得並處理回傳資料,可視需求挑選使用。