使用ajax實(shí)現(xiàn)表單提交無刷新頁面在項(xiàng)目中經(jīng)常會(huì)用到。前一段時(shí)間跟著師傅學(xué)到了另外幾種無刷新提交表單的方法,主要是基于iframe框架實(shí)現(xiàn)的?,F(xiàn)在整理出來分享給大家。
第一種:
(html頁面)
HTML Code
1.<!DOCTYPE HTML>
2.<html lang="en-US">
3.<head>
4.<meta charset="utf-8">
5.<title>無刷新提交表單</title>
6.<style type="text/css">
7.ul{ list-style-type:none;}
8.</style>
9.</head>
10.<body>
11.<iframe name="formsubmit" style="display:none;">
12.</iframe>
13.<!-- 將form表單提交的窗口指向隱藏的ifrmae,并通過ifrmae提交數(shù)據(jù)。 -->
14.<form action="form.php" method="POST" name="formphp" target="formsubmit">
15.<ul>
16.<li>
17.<label for="uname">用戶名:</label>
18.<input type="text" name="uname" id="uname" />
19.</li>
20.<li>
21.<label for="pwd">密 碼:</label>
22.<input type="password" name="pwd" id="pwd" />
23.</li>
24.<li>
25.<input type="submit" value="登錄" />
26.</li>
27.</ul>
28.</form>
29.</body>
30.</html>
31.
32.(PHP頁面:form.php)
33.
34.<?php
35.//非空驗(yàn)證
36.if(empty($_POST['uname']) || empty($_POST['pwd']))
37.{
38.echo '<script type="text/javascript">alert("用戶名或密碼為空!");</script>';
39.exit;
40.}
41.//驗(yàn)證密碼
42.if($_POST['uname'] != 'jack' || $_POST['pwd'] != '123456')
43.{
44.echo '<script type="text/javascript">alert("用戶名或密碼不正確!");</script>';
45.exit;
46.} else {
47.echo '<script type="text/javascript">alert("登錄成功!");</script>';
48.exit;
49.}
第二種:
(html頁面)
HTML Code
1.<!DOCTYPE HTML>
2.<html lang="en-US">
3.<head>
4.<meta charset="utf-8">
5.<title>iframe提交表單</title>
6.</head>
7.<body>
8.<iframe name="myiframe" style="display:none;" onload="iframeLoad(this);"></iframe>
9.<form action="form.php" target="myiframe" method="POST">
10.用戶名:<input type="text" name="username" /><br/>
11.密 碼:<input type="password" name="userpwd" /><br/>
12.<input type="submit" value="登錄" />
13.</form>
14.<script type="text/javascript">
15.function iframeLoad(iframe){
16.var doc = iframe.contentWindow.document;
17.var html = doc.body.innerHTML;
18.if(html != ''){
19.//將獲取到的json數(shù)據(jù)轉(zhuǎn)為json對(duì)象
20.var obj = eval("("+html+")");
21.//判斷返回的狀態(tài)
22.if(obj.status < 1){
23.alert(obj.msg);
24.}else{
25.alert(obj.msg);
26.window.location.;
27.}
28.}
29.}
30.</script>
31.</body>
32.</html>
(PHP頁面:form.php)
XML/HTML Code
1.<?php
2.//設(shè)置時(shí)區(qū)
3.date_default_timezone_set('PRC');
4./*
5.返回的提交消息
6.status:狀態(tài)
7.msg:提示信息
8.*/
9.$msg = array('status'=>0,'msg'=>'');
10.//獲取提交過來的數(shù)據(jù)
11.$name = $_POST['username'];
12.$pwd = $_POST['userpwd'];
13.//模擬登錄驗(yàn)證
14.$user = array();
15.$user['name'] = 'jack';
16.$user['pwd'] = 'jack2014';
17.if($name != $user['name']){
18.$msg['msg'] = '該用戶未注冊(cè)!';
19.$str = json_encode($msg);
20.echo $str;
21.exit;
22.}else if($pwd != $user['pwd']){
23.$msg['msg'] = '輸入的密碼錯(cuò)誤!';
24.$str = json_encode($msg);
25.echo $str;
26.exit;
27.}
28.$msg['msg'] = '登錄成功!';
29.$msg['status'] = 1;
30.$str = json_encode($msg);
31.echo $str;
以上內(nèi)容是小編給大家介紹的基于HTML實(shí)現(xiàn)表單提交后無刷新頁面的相關(guān)內(nèi)容,希望對(duì)大家有所幫助!