iframe無刷新提交表單,iframe仿ajax提交表單

本文摘要

使用ajax能夠實現無刷新提交表單,但有人表示ajax的效率不行,或者是其餘缺點,例如客戶端臃腫,太多客戶段代碼形成開發上的成本,若是網速慢,則會出現ajax請求緩慢,頁面空白的狀況,對客戶的體驗很差。ajax請求不利於搜索引擎優化,通常搜不到ajax添加到頁面的信息。php

此次就介紹一下iframe仿造ajax異步請求,實際上iframe是同步請求,只是把提交的跳轉,發生在iframe的可視區域內。css

代碼

index.htmlhtml

<!DOCTYPE html>
<html>
<head>
    <title>iframe提交表單</title>
    <meta charset="utf-8">
    <style type="text/css">
        #result{
            border: none; /*去掉默認的邊框*/
            width: 300px; /*可視區域的寬度*/
            height: 60px; /*可視區域的高度*/
        }
    </style>
</head>
<body>
<!-- 表單 -->
<h1>iframe提交表單</h1>
<form action="check.php" method="post" target='result'>
    <input type="text" class="input_css" name="user" placeholder="請輸入帳號"><br/>
    <input type="password" class="input_css" name="pwd" placeholder="請輸入密碼"><br/>
    <input type="submit" class="formbtn" value="登錄"><br/>
</form>

<!-- 用於查看提交結果 -->
<iframe name='result' id="result" scrolling="no"></iframe>
</body>
</html>

check.phpajax

<style type="text/css">
*{
    margin:0;
    padding:0;
}
</style>
<?php
// 設置編碼
header("Content-type:text/html;charset=utf-8");

// 得到POST過來的登錄所需參數
$user = $_POST["user"];
$pwd = $_POST["pwd"];

// 過濾參數
if ($user == '' && $pwd == '') {
    echo "<p style='color:#f00;font-size:15px;margin-top:10px;'>帳號和密碼不得爲空</p>";
}else if ($user == '' ) {
    echo "<p style='color:#f00;font-size:15px;margin-top:10px;'>帳號不得爲空</p>";
}else if ($pwd == '' ) {
    echo "<p style='color:#f00;font-size:15px;margin-top:10px;'>密碼不得爲空</p>";
}else{
    echo "<p style='color:#000;font-size:15px;margin-top:10px;'>你提交的帳號是:".$user."<br/>你提交的密碼是:".$pwd."</p>";
}
?>

image.png
image.png
image.png

動圖演示

image

在線演示

http://www.likeyunba.com/demo...segmentfault

本文做者

Author:TANKING
Date:2021-01-13
Wechat:sansure2016
Web:http://www.likeyun.cn/
Qrcode:Join inapp

相關文章
相關標籤/搜索