Ajax PHP項目實戰


    這兩天在實驗樓學習ajax,后台是用php寫的,下面我將三個實戰項目分享出來,也方便我以后隨時查看。

    第一個項目我寫的注釋比較詳細,第二個和第三個注釋就寫的比較少了,因為用的方法都差不多;這三個項目都是我們經常看到的,針對我們做測試的朋友來說,大部分是不知道這個到底是怎么實現的(當然包括我自己);我們經過不斷的學習代碼,知道功能是怎么實現的,我們測試起來也就輕松得多,也就不會提出一些很小白的問題,被developer笑了。

    好了下面就是三個項目,中間有什么問題希望大家不吝賜教:

一、環境准備:

1、搭建php開發環境, WampServer:

安裝詳情:http://jingyan.baidu.com/article/2d5afd69efe9cf85a3e28e54.html

2、准備數據

連接mysql數據庫之后、創建數據庫,表:

創建數據庫 ajaxtest

create database ajaxtest default charset utf8;

 

use ajaxtest;

 

創建ajaxtable表:

create table ajaxtable(

userid int(11) not null auto_increment

username varchar(50) not null,

userpass varchar(50) not null,

userage int(11) not null,

usersex varchar(1) not null,

primary key(userid)

);

 

插入數據:

insert into ajaxtable values(1,'張三','lisi','28','女');

insert into ajaxtable values(2,'張一','lisi','18','男');

insert into ajaxtable values(3,'張二','lisi','18','女');

insert into ajaxtable values(4,'王一','lisi','18','男');

insert into ajaxtable values(5,'王二','lisi','18','女');

insert into ajaxtable values(6,'王三','lisi','18','女');

insert into ajaxtable values(7,'王四','lisi','18','女');

insert into ajaxtable values(8,'王五','lisi','18','女');

insert into ajaxtable values(9,'李四','lisi','18','男');

insert into ajaxtable values(10,'六三','lisi','18','女');

insert into ajaxtable values(11,'楊思','lisi','18','男');

二、Ajax—PHP實戰1:   

目的:在頁面輸入年齡、性別值,利用ajax發送請求,查詢出滿足條件的數據:

結果演示:

 

我的項目路徑是:

 

所以訪問的url:http://localhost/ajaxtest/ajaxpro1/index.html

創建index.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>ajaxtest</title>
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <script language="JavaScript" type="text/javascript">
 8         function ajaxFunction(){
 9             //該函數將頁面的輸入年齡和性別的值發送到ajaxtest.php中,然后返回查詢的結果
10             var xmlhttp;//定義一個xmlhttp變量
11             try{
12                 xmlhttp = new XMLHttpRequest();//一個XMLHttpRequest對象
13             }catch (e){
14                 try{
15                     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//這個主要是針對ie瀏覽器低版本的
16                 }catch (e){
17                     alert("你的游覽器不支持");
18                     return false;
19                 }
20             }
21 //
22 //            如果readyState狀態改變,那就會觸發onreadystatechange事件
23 //            readyState的狀態:
24 //            0: 請求未初始化
25 //            1: 服務器連接已建立
26 //            2: 請求已接收
27 //            3: 請求處理中
28 //            4: 請求已完成,且響應已就緒
29             xmlhttp.onreadystatechange = function () {
30                 if(xmlhttp.readyState == 4){
31                     //如果readyState的狀態為4,獲取id為ajaxDiv的元素
32                     var ajaxDisplay = document.getElementById('ajaxDiv');
33                     //將查詢的結果返回,顯示
34                     ajaxDisplay.innerHTML = xmlhttp.responseText;
35                 }
36             }
37             //獲取id為userage的元素,也就是年齡的值
38             var userage = document.getElementById('userage').value;
39             //獲取id為usersex的元素,也就是性別的值
40             var usersex = document.getElementById('usersex').value;
41             //拼接請求的url
42             var url = "?userage=" + userage;
43             url += "&usersex=" + usersex;
44             //准備請求
45             xmlhttp.open("GET", "ajaxtest.php" + url, true);
46             //將請求發送到服務器
47             xmlhttp.send();
48         }
49     </script>
50 
51 </head>
52 <body>
53 <form name="myform">
54     Age: <input type="text" name="userage" id="userage"><br><br>
55     Sex: <select id="usersex" name="usersex">
56     <option value="男"></option>
57     <option value="女"></option>
58 </select>
59     <br><br>
60     <input type="button" onclick="ajaxFunction()" value="執行">
61 </form>
62 <div id="ajaxDiv">顯示執行ajax結果</div>
63 </body>
64 </html>

創建:ajaxtest.php

 1 <?php
 2 /**
 3  * Created by PhpStorm.
 4  * User: xxx
 5  * Date: 2016/10/10
 6  * Time: 10:52
 7  */
 8 
 9 error_reporting(0);//禁用錯誤報告
10 # database message
11 // 數據庫連接信息
12 $dbhost = "localhost";
13 $dbuser = "root";
14 $dbpswd = "123456";
15 $dbname = "ajaxtest";
16 
17 // 獲取ajax請求傳入的參數
18 $userage = $_GET['userage'];
19 $usersex = $_GET['usersex'];
20 
21 $mysqli = new mysqli();
22 // 連接數據庫
23 $mysqli->connect($dbhost, $dbuser, $dbpswd, $dbname);
24 if($mysqli->error){
25     echo "連接數據庫失敗<br>".$mysqli->error;
26 }
27 // 設置utf8編碼
28 $mysqli->set_charset("utf8");
29 // sql語句
30 $query = "select * from ajaxtable where usersex = '$usersex'";
31 
32 # 判斷userage是否是個數字
33 if(is_numeric($userage)){
34     $query .= " AND userage <= '$userage'";
35 }
36 # 查詢數據
37 $result = $mysqli->query($query);
38 # 顯示列表頭
39 $display_string = "<table>";
40 $display_string .= "<tr>";
41 $display_string .= "<th>用戶名</th>";
42 $display_string .= "<th>年齡</th>";
43 $display_string .= "<th>性別</th>";
44 $display_string .= "</tr>";
45 
46 # 顯示內容
47 while ($row = $result->fetch_array()){
48     $display_string .= "<tr>";
49     $display_string .= "<td>".$row['username']."</td>";
50     $display_string .= "<td>".$row['usersex']."</td>";
51     $display_string .= "<td>".$row['userage']."</td>";
52     $display_string .= "</tr>";
53 }
54 $display_string .= "</table>";
55 echo "SQL語句為:".$query."<br>";
56 echo $display_string;
57 
58 // 釋放查詢結果
59 $result->close();
60 // 關閉mysql連接
61 $mysqli->close();

三、Ajax—PHP實戰2:

目的:輸入用戶名,驗證數據庫是否存在,有相應的提示

url: http://localhost/ajaxtest/ajaxpro2/index.html

執行結果:

項目路徑:

創建index.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Ajax表單驗證</title>
 6     <!--引入css文件:mycss.css-->
 7     <link href="mycss.css" rel="stylesheet" type="text/css">
 8     <script>
 9         function showHint() {
10             // 獲取用戶名輸入框的值
11             var str = document.getElementById("username").value;
12             if (str.length == 0){
13                 // 如果輸入框值為空的時候,提示
14                 document.getElementById("showmsg").innerHTML = "用戶名不能為空";
15                 return;
16             }else {
17                 // ajax發送請求
18                 var xmlhttp = new XMLHttpRequest();
19                 xmlhttp.onreadystatechange = function () {
20                     if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
21                         document.getElementById('showmsg').style.display = "block";
22                         document.getElementById('showmsg').innerHTML = xmlhttp.responseText;
23                     }
24                 }
25                 xmlhttp.open("GET", "ajaxtest.php?username=" + str, true);
26                 xmlhttp.send();
27             }
28 
29         }
30     </script>
31 </head>
32 <body>
33     <div class="container">
34         <form id="contact" method="post">
35             <input type="text" placeholder="用戶名" id="username" name="username" onblur="showHint()">
36             <div id="showmsg" style="display: none"></div>
37         </form>
38     </div>
39 </body>
40 </html>

創建mycss.css文件:

 1 * {
 2     margin: 0;
 3     padding: 0;
 4     box-sizing: border-box;
 5     -webkit-box-sizing: border-box;
 6     -moz-box-sizing: border-box;
 7     -webkit-font-smoothing: antialiased;
 8 }
 9 
10 body {
11     font-family: Arial,sans-serif;
12     font-weight: 300;
13     font-size: 12px;
14     line-height: 30px;
15 }
16 
17 .container {
18     max-width: 400px;
19     position: relative;
20 }
21 
22 #contact {
23     background: #F9F9F9;
24     padding: 25px;
25     margin: 5px 0;
26 }
27 
28 #contact input[type="text"] {
29     border: 1px solid #AAA;
30     width: 200px;
31     height: 25px;
32 }
33 
34 #contact input:focus, #contact textarea:focus {
35     outline:0;
36     border:1px solid #999;
37 }
38 ::-webkit-input-placeholder {
39     color:#888;
40 }
41 :-moz-placeholder {
42     color:#888;
43 }
44 ::-moz-placeholder {
45     color:#888;
46 }
47 :-ms-input-placeholder {
48     color:#888;
49 }

創建ajaxtest.php文件:

 1 <?php
 2 /**
 3  * Created by PhpStorm.
 4  * User: xxx
 5  * Date: 2016/10/11
 6  * Time: 9:00
 7  */
 8 error_reporting(0);
 9 $dbhost = "localhost";
10 $dbuser = "root";
11 $dbpswd = "123456";
12 $dbname = "ajaxtest";
13 
14 $checkmsg = $_GET['username'];
15 
16 $myselect = new mysqli();
17 $myselect->connect($dbhost,$dbuser,$dbpswd,$dbname);
18 $myselect->set_charset("utf8");
19 $sql = "select * from ajaxtable where username='$checkmsg'";
20 $result = $myselect->query($sql);
21 
22 $rownum = $result->num_rows;
23 //echo $rownum;
24 if($rownum >= 1){
25     echo '<font color="red">用戶名已存在</font>';
26 }else{
27     echo '<font color="green">用戶名可用</font>';
28 }
29 
30 $result->close();
31 $myselect->close();

四、Ajax—PHP實戰3:

目的:根據輸入的值進行搜索,顯示出搜索結果,並且可以點擊下拉框中的值可以跳轉到新的頁面;也可以根據輸入的值,點擊搜索按鈕,進入結果頁面。

結果演示:

項目路徑:

訪問Url:http://localhost/ajaxtest/ajaxpro3/index.html

創建index.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Ajax搜索</title>
 6     <link href="mycss.css" rel="stylesheet" type="text/css">
 7     <script>
 8         function showHint(str) {
 9             if(str.length==0){
10                 document.getElementById("showmsg").innerHTML = "";
11                 return;
12             }else {
13                 var xmlhttp = new XMLHttpRequest();
14                 xmlhttp.onreadystatechange = function () {
15                     if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
16                         document.getElementById("showmsg").style.display = "block";
17                         document.getElementById("showmsg").innerHTML = xmlhttp.responseText;
18                     }
19                 }
20                 xmlhttp.open("GET","ajaxtest.php?keywords=" + str,true);
21                 xmlhttp.send();
22             }
23         }
24     </script>
25 </head>
26 <body>
27     <form action="result.php" method="get">
28         <input type="text" name="keywords" id="keywords" onkeyup="showHint(this.value)">
29         <input type="submit" name="submit" id="submit" value="搜索">
30         <div id="showmsg" style="display: none"></div>
31     </form>
32 
33 </body>
34 </html>

創建mycss.css

 1 body {
 2     color: #555;
 3 }
 4 
 5 #keywords {
 6     width: 485px;
 7     height: 28px;
 8     margin: 0px;
 9     font-size: 14px;
10 }
11 
12 #showmsg {
13     display: block;
14     border: solid 1px #B0B0B0;
15     width: 487px;
16     line-height: 28px;
17     font-size: 14px;
18 }
19 
20 #submit{
21     width: 90px;
22     height: 30px;
23 }
24 
25 a:link{ text-decoration: none; color: blue}
26 a:active{ text-decoration: blink;}
27 a:visited {text-decoration: none; color: green}
28 a:hover{ text-decoration: underline; color: red}

創建ajaxtest.php

 1 <?php
 2 /**
 3  * Created by PhpStorm.
 4  * User: LSH
 5  * Date: 2016/10/11
 6  * Time: 11:00
 7  */
 8 error_reporting(0);
 9 $dbhost = "localhost";
10 $dbuser = "root";
11 $dbpswd = "123456";
12 $dbname = "ajaxtest";
13 
14 $checkmsg = $_GET['keywords'];
15 
16 $myselect = new mysqli();
17 $myselect->connect($dbhost,$dbuser,$dbpswd,$dbname);
18 $myselect->set_charset("utf8");
19 $sql = "select * from ajaxtable where username LIKE '%$checkmsg%'";
20 $result = $myselect->query($sql);
21 
22 $rownum = $result->num_rows;
23 //echo $rownum;
24 if($rownum < 1){
25     echo "數據庫無數據";
26 }else if($rownum == 1){
27     $row = $result->fetch_array();
28     echo "<a href='result.php?keywords=".$row['username']."'>".$row['username']."</a>";
29 }else{
30     while ($row = $result->fetch_array()){
31         echo "<a href='result.php?keywords=".$row['username']."'>".$row['username']."</a>"."<br>";
32     }
33 }
34 
35 $result->close();
36 $myselect->close();

創建result.php:

 1 <?php
 2 /**
 3  * Created by PhpStorm.
 4  * User: LSH
 5  * Date: 2016/10/11
 6  * Time: 11:00
 7  */
 8 error_reporting(0);
 9 $dbhost = "localhost";
10 $dbuser = "root";
11 $dbpswd = "123456";
12 $dbname = "ajaxtest";
13 
14 $checkmsg = $_GET['keywords'];
15 
16 $myselect = new mysqli();
17 $myselect->connect($dbhost,$dbuser,$dbpswd,$dbname);
18 $myselect->set_charset("utf8");
19 $sql = "select * from ajaxtable where username LIKE '%$checkmsg%'";
20 $result = $myselect->query($sql);
21 
22 //echo $sql;
23 ?>
24 <!DOCTYPE html>
25 <html lang="en">
26 <head>
27     <meta charset="UTF-8">
28     <title>查詢結果</title>
29     <link href="mycss.css" rel="stylesheet" type="text/css">
30 </head>
31 <body>
32 <?php
33 //echo $result->num_rows;
34     while ($row = $result->fetch_array()){
35         echo "<div><h1>姓名:$row[username]</h1><p>年齡:$row[userage],性別:$row[usersex]</p></div><br>";
36     }
37 $result->close();
38 $myselect->close();
39 ?>
40 </body>
41 </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM