通常對(duì)于無(wú)刷新提交表單,我們都是運(yùn)用ajax實(shí)現(xiàn)的。前段時(shí)間跟著老大了解到另一種無(wú)刷新提交表單的方法,是利用iframe框架實(shí)現(xiàn)的?,F(xiàn)在整理出來(lái)分享給大家。
第一種:
html頁(yè)面
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>無(wú)刷新提交表單</title>
<style type="text/css">
ul{ list-style-type:none;}
</style>
</head>
<body>
<iframe name="formsubmit" style="display:none;">
</iframe>
<!-- 將form表單提交的窗口指向隱藏的ifrmae,并通過(guò)ifrmae提交數(shù)據(jù)。 -->
<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頁(yè)面:form.php
<?php
//非空驗(yàn)證
if(empty($_POST['uname']) || empty($_POST['pwd']))
{
echo '<script type="text/javascript">alert("用戶名或密碼為空!");</script>';
exit;
}
//驗(yàn)證密碼
if($_POST['uname'] != 'jack' || $_POST['pwd'] != '123456')
{
echo '<script type="text/javascript">alert("用戶名或密碼不正確!");</script>';
exit;
} else {
echo '<script type="text/javascript">alert("登錄成功!");</script>';
exit;
}
第二種:
html頁(yè)面
<!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數(shù)據(jù)轉(zhuǎn)為json對(duì)象
var obj = eval("("+html+")");
//判斷返回的狀態(tài)
if(obj.status < 1){
alert(obj.msg);
}else{
alert(obj.msg);
window.location.;
}
}
}
</script>
</body>
</html>
PHP頁(yè)面:form.php
<?php
//設(shè)置時(shí)區(qū)
date_default_timezone_set('PRC');
/*
返回的提交消息
status:狀態(tài)
msg:提示信息
*/
$msg = array('status'=>0,'msg'=>'');
//獲取提交過(guò)來(lái)的數(shù)據(jù)
$name = $_POST['username'];
$pwd = $_POST['userpwd'];
//模擬登錄驗(yàn)證
$user = array();
$user['name'] = 'jack';
$user['pwd'] = 'jack2014';
if($name != $user['name']){
$msg['msg'] = '該用戶未注冊(cè)!';
$str = json_encode($msg);
echo $str;
exit;
}else if($pwd != $user['pwd']){
$msg['msg'] = '輸入的密碼錯(cuò)誤!';
$str = json_encode($msg);
echo $str;
exit;
}
$msg['msg'] = '登錄成功!';
$msg['status'] = 1;
$str = json_encode($msg);
echo $str;
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家學(xué)習(xí)php程序設(shè)計(jì)有所幫助。