HTML無刷新提交表單

一般對於無刷新提交表單,咱們都是運用ajax實現的。前段時間跟着老大瞭解到另外一種無刷新提交表單的方法,是利用iframe框架實現的。如今整理出來分享給你們。javascript

第一種:php

(html頁面)css

複製代碼
複製代碼
<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="utf-8">
    <title>無刷新提交表單</title>
    <style type="text/css">
        ul{ list-style-type:none;}
    </style>
</head>
<body>
    <iframe name="formsubmit" style="display:none;">
    </iframe>
    
<!-- 將form表單提交的窗口指向隱藏的ifrmae,並經過ifrmae提交數據。 --> <form action="form.php" method="POST" name="formphp" target="formsubmit"> <ul> <li> <label for="uname">用戶名:</label> <input type="text" name="uname" id="uname" /> </li> <li> <label for="pwd">密 碼:</label> <input type="password" name="pwd" id="pwd" /> </li> <li> <input type="submit" value="登陸" /> </li> </ul> </form> </body> </html>
複製代碼
複製代碼

(PHP頁面:form.php)html

複製代碼
複製代碼
<?php
  //非空驗證
  if(empty($_POST['uname']) || empty($_POST['pwd']))
  {
    echo '<script type="text/javascript">alert("用戶名或密碼爲空!");</script>';
    exit;
  }
  
  //驗證密碼
  if($_POST['uname'] != 'jack' || $_POST['pwd'] != '123456')
  {
    echo '<script type="text/javascript">alert("用戶名或密碼不正確!");</script>';
    exit;
  } else {
    echo '<script type="text/javascript">alert("登陸成功!");</script>';
    exit;
  }
  
  
複製代碼
複製代碼

 

第二種:java

(html頁面)ajax

複製代碼
複製代碼
<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="utf-8">
    <title>iframe提交表單</title>
</head>
<body>
    <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 type="text/javascript">
     function iframeLoad(iframe){
        var doc = iframe.contentWindow.document;
        var html = doc.body.innerHTML;
        if(html != ''){
          //將獲取到的json數據轉爲json對象
          var obj = eval("("+html+")");
          //判斷返回的狀態
          if(obj.status < 1){
            alert(obj.msg);
          }else{
            alert(obj.msg);
            window.location.href="http://www.baidu.com";
          }
        }
     }
    </script>
</body>
</html>
複製代碼
複製代碼

(PHP頁面:form.php)json

複製代碼
複製代碼
<?php
  //設置時區
  date_default_timezone_set('PRC');
  /*
    返回的提交消息
    status:狀態
    msg:提示信息
  */
  $msg = array('status'=>0,'msg'=>'');
  
  //獲取提交過來的數據
  $name = $_POST['username'];
  $pwd = $_POST['userpwd'];
  
  //模擬登陸驗證
  $user = array();
  $user['name'] = 'jack';
  $user['pwd'] = 'jack2014';
  
  if($name != $user['name']){
    $msg['msg'] = '該用戶未註冊!';
    $str = json_encode($msg);
    echo $str;
    exit;
  }else if($pwd != $user['pwd']){
    $msg['msg'] = '輸入的密碼錯誤!';
    $str = json_encode($msg);
    echo $str;
    exit;
  }
  
  $msg['msg'] = '登陸成功!';
  $msg['status'] = 1;
  $str = json_encode($msg);
  echo $str;
複製代碼
相關文章
相關標籤/搜索