1. 程式人生 > >PHP(PDO)-MySQL-jQuery Ajax getJSON綜合示例

PHP(PDO)-MySQL-jQuery Ajax getJSON綜合示例

實現一個簡單的mysql資料庫內容管理功能。通過jQuery的Ajax實現單頁應用。具體程式碼如下:
0.建立資料庫程式碼

-- phpMyAdmin SQL Dump
-- version phpStudy 2014
-- http://www.phpmyadmin.net
--
-- 主機: localhost
-- 生成日期: 2017 年 05 月 06 日 02:57
-- 伺服器版本: 5.5.35
-- PHP 版本: 5.3.28

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @
[email protected]
@CHARACTER_SET_CLIENT */
; /*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */; /*!40101 SET @[email protected]@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- 資料庫: `test` -- CREATE DATABASE `test` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `test`; -- --------------------------------------------------------
-- -- 表的結構 `news` -- -- 建立時間: 2017 年 05 月 05 日 15:09 -- 最後更新: 2017 年 05 月 05 日 18:15 -- CREATE TABLE IF NOT EXISTS `news` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(100) COLLATE utf8_bin NOT NULL, `content` text COLLATE utf8_bin NOT NULL, `author` varchar(100) COLLATE utf8_bin NOT NULL, `postTime`
datetime NOT NULL, `clickRate` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=4 ;
-- -- 轉存表中的資料 `news` -- INSERT INTO `news` (`id`, `title`, `content`, `author`, `postTime`, `clickRate`) VALUES (1, '中華人民共和國', '311111', '11111', '2017-05-06 00:00:00', 0), (2, '2222222222', '2222', '2', '2017-05-06 00:00:00', 0), (3, '3333333333', '3', '3', '2017-05-06 00:00:00', 0); /*!40101 SET [email protected]_CHARACTER_SET_CLIENT */; /*!40101 SET [email protected]_CHARACTER_SET_RESULTS */; /*!40101 SET [email protected]_COLLATION_CONNECTION */;

1.index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>PHP-MySQL-jQuery Ajax簡單示例</title>
        <link rel="stylesheet" type="text/css" href="css/index.css"/>
        <script src="js/jquery-1.9.0.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="js/index.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body>
       <h1>資料表內容的操作</h1>
       <fieldset>
           <legend>已有內容列表</legend>
           <ul id="listBox">
           </ul>
       </fieldset>
       <fieldset>
            <legend>編輯區域</legend>
            <div id="editBox">
                <!--下面這個型別為hidden的input用於修改記錄時記下記錄的id值,頁面上是不可見的-->
                <input type="hidden" name="newsId" id="newsId" value="" />
                <table>
                    <tr>
                        <th>標題</th>
                        <td><input type="text" name="newsTitle" id="newsTitle" value="" /></td>
                    </tr>
                    <tr>
                        <th>內容</th>
                        <td><textarea id="newsContent"></textarea></td>
                    </tr>
                    <tr>
                        <th>作者</th>
                        <td><input type="text" name="newsAuthor" id="newsAuthor" value="" /></td>
                    </tr>
                    <tr>
                        <th>日期</th>
                        <td><input type="text" name="newsPostTime" id="newsPostTime" value="" /></td>
                    </tr>
                    <tr>
                        <td colspan="2" align="center"><button id="add">新增</button><button id="update">修改</button><button id="reset">清空</button></td>
                    </tr>
                </table>
                <div id="tip">
                    &nbsp;
                </div>
            </div>
       </fieldset>
    </body>
</html>

2.js/index.js

$(function() {
    //初始化時呼叫讀取函式 讀取已有記錄
    loadListBox();

    //點選“新增”按鈕事件
    $("#add").click(function(){
        addNewRecord(); //呼叫方法(函式)

    //點選“修改”按鈕事件
    $("#update").click(function(){
        updateRecord();//呼叫方法(函式)
    })

    //點選“清空”按鈕事件
    $("#reset").click(function(){
        $("#editBox input").val(""); //將#editBox下包含的所有input標籤的值置為空
        $("#editBox input:eq(1)").focus(); //使#editBox下的第2個input(因為第一個input是hidden),即標題後的方框獲得焦點
    })

    //讀取已有記錄的方法
    function loadListBox() {
        /*
         方法名:$.getJSON()
         引數:(url,data,function)
         引數含義:url:能夠處理資料的動態頁面檔案,如xxx.php;
             data:要傳送給上述頁面處理的引數,格式為:{key:value,key:value,...}。其中key作為變數名在php頁面中可據此接收變數值。
             function:動態頁面檔案處理成功後的返回函式,可以有引數,引數為動態頁面的返回值(json格式),常用於對返回值進行顯示處理。
         * */
        $.getJSON("php/index.php", {
            act: "read"
        }, function(rs) { //rs為上述index.php頁面處理的的返回值
            $tempStr = "";//臨時字串變數
            if(rs.data.length == 0) { //如果返回值中data元素的長度為為0,說明返回值為空。data元素在php程式碼中定義
                $tempStr = "<li>暫無資料</li>";
            }
            else//否則說明返回值不為空
            {
                for(i in rs.data) {//通過迴圈,根據返回值生成html字串
                    //下句中把buton的name屬性設定為當前記錄的id值,用特殊用途
                    $tempStr += "<li><a href='read.html?id="+rs.data[i]['id']+"'>" + rs.data[i]['title'] + "</a> <button name="+rs.data[i]['id']+">修改</button></li>";
                }
            }
            $("#listBox").html($tempStr);//把得到的html字串顯示到#listBox中

            //緊接著,下用的程式碼用於實現使用者點選某記錄後的“修改”按鈕後,把該條記錄已有內容填入右側表單中
            $("#listBox li").each(function(){ //遍歷li
                $(this).find("button").on("click",function(){ //在當前li中找出button元素,並繫結單擊事件
                    var curId=$(this).prop("name"); //獲取當前按鈕的name屬性值,即當前記錄的id值
                    //獲取當前記錄的全部內容,並顯示在表單中
                    $.getJSON("php/index.php",{act:"pullSingleRecord",id: curId},function  (rs) {
                        if(rs.data.length==0)//判斷返回值是否為空。如果為空,
                        {
                            $("#tip").delay(0).fadeIn();//顯示用於提示的元素
                            $("#tip").text("資料拉取失敗,請重試或聯絡管理員。");//設定提示資訊
                            $("#tip").delay(5000).fadeOut();//5秒後,提示元素消失
                        }
                        else //如果返回值不為空
                        {
                            //把返回值填入表單中
                            $("#newsId").val(curId);
                            $("#newsTitle").val(rs.data[0]['title']);
                            $("#newsContent").val(rs.data[0]['content']);
                            $("#newsAuthor").val(rs.data[0]['author']);
                            $("#newsPostTime").val(rs.data[0]['postTime']);
                            //顯示提示資訊
                            $("#tip").delay(0).fadeIn();
                            $("#tip").text("資料拉取成功,請直接修改各欄位內容,完成後點選“修改”按鈕。");
                            $("#tip").delay(5000).fadeOut();
                        }
                    })
                })
            })
        })
    }

    //新增記錄的方法
    function addNewRecord()
    {
        $.getJSON("php/index.php",{act:"add",title:$("#newsTitle").val(),content:$("#newsContent").val(),author:$("#newsAuthor").val(),postTime:$("#newsPostTime").val()},function(rs){
            if(rs.status=="ok") //如果返回值中status值為ok,說明執行成功
            {
                loadListBox();//重新整理列表欄
                //顯示提示資訊
                $("#tip").delay(0).fadeIn();
                $("#tip").text("成功新增一條記錄。");
                $("#tip").delay(5000).fadeOut();
            }
            else //否則
            {
                //只顯示提示資訊,不用重新整理列表欄
                $("#tip").delay(0).fadeIn();
                $("#tip").text("新增記錄失敗,請重試或聯絡管理員。");
                $("#tip").delay(5000).fadeOut();
            }

        });
    }

    //修改記錄的方法
    function updateRecord () {
        //修改記錄時,需要把表單中的內容提交到php頁面。
        $.getJSON("php/index.php",{act:"update",id:$("#newsId").val(),title:$("#newsTitle").val(),content:$("#newsContent").val(),author:$("#newsAuthor").val(),postTime:$("#newsPostTime").val()},function(rs){
            if(rs.status=="ok")
            {
                loadListBox();
                $("#tip").delay(0).fadeIn();
                $("#tip").text("成功修改一條記錄。");
                $("#tip").delay(5000).fadeOut();
            }
            else
            {
                $("#tip").delay(0).fadeIn();
                $("#tip").text("修改記錄失敗,請重試或聯絡管理員。");
                $("#tip").delay(5000).fadeOut();
            }
        })
    }
})

3.php/index.php

<?php
$dbh=new PDO("mysql:host=localhost;dbname=test","root","root");//pdo方式建立資料庫連線
$dbh->query("set names utf8");//設定資料庫端的字元編碼為utf8,必須這樣寫,否則頁面顯示的漢字為亂碼

//以下語句中的$_GET['act']變數是接收js傳來的使用者操作型別值
if(@$_GET['act']=='read') //如果使用者操作型別是讀取已有內容
{
    $sql="select * from news"; //查詢已有內容的sql語句
    $rs=$dbh->query($sql)->fetchAll();//執行sql

    //返回查詢結果。由於js程式碼中是用getJSON來請求php程式碼的,所以php頁面的處理結果必須為json格式,否則js無法接收
    //json_encode()函式的作用是把變數格式化為json型別。array函式是把引數變數轉為陣列型別;"data"=>$rs是在json中建立一個key-value對
    //可以看出,data鍵的值是查詢結果,sql鍵的值是sql語句本身
    echo json_encode(array("data"=>$rs,"sql"=>$sql));
}

//新增記錄
else if(@$_GET['act']=='add') //如果使用者操作型別是新增記錄,即點選了“新增”按鈕
{
    //獲取使用者在表單中輸入的值。注意與js中變數名稱要一致
    $newTitle[email protected]$_GET['title'];
    $newContent[email protected]$_GET['content'];
    $newAuthor[email protected]$_GET['author'];
    $newPostTime[email protected]$_GET['postTime'];
    $sql="insert into news values(null,'$newTitle','$newContent','$newAuthor','$newPostTime',0)";
    $rs=$dbh->exec($sql);//注意執行insert update的方法與執行select不同。這裡的返回值是多少行受影響。
    if($rs==1) //如果有一行受到影響,說明此條記錄修改成功
        //設定返回值
        echo json_encode(array("sql"=>$sql,"status"=>"ok"));
    else //如果沒有任何一行受到影響,說明修改失敗
        echo json_encode(array("sql"=>$sql,"status"=>"fail"));
}
//拉取要修改的記錄
else if(@$_GET['act']=="pullSingleRecord") //說明使用者點選了某條記錄後的“修改”按鈕
{
    $sql="select * from news where id="[email protected]$_GET['id'];//注意後面要接收js傳來的當前記錄的id值
    $rs=$dbh->query($sql)->fetchAll();//查詢該id的所有欄位值
    //返回查詢結果
    echo json_encode(array("data"=>$rs,"sql"=>$sql));
}
//修改記錄
else if(@$_GET['act']=='update')//說明使用者點選了表單下面的“修改按鈕”
{
    //獲取使用者在表單中輸入的值。注意一定要接收js傳來的當前記錄的id值
    $newsId[email protected]$_GET['id'];
    $newTitle[email protected]$_GET['title'];
    $newContent[email protected]$_GET['content'];
    $newAuthor[email protected]$_GET['author'];
    $newPostTime[email protected]$_GET['postTime'];
    //注意此sql語句後面的where條件的寫法,由於id欄位是int型,所以不能在外層加''
    $sql="update news set title='$newTitle',content='$newContent',author='$newAuthor',postTime='$newPostTime' where id=$newsId";
    $rs=$dbh->exec($sql);
    if($rs==1)
        echo json_encode(array("sql"=>$sql,"status"=>"ok"));
    else
        echo json_encode(array("sql"=>$sql,"status"=>"fail"));
}

?>

4.css/index.css

body{
    margin: 0px;
    font:16px "microsoft yahei";
}
h1
{
    font:bold 20px "microsoft yahei";
}
fieldset
{
    width: 44%;
    margin: 5px;
    float: left;
    border-radius: 5px;
}
legend
{
    color: #1f80bf;
    font-weight:bold;
}
ul,li
{
    margin: 0px;
    padding: 0px;
    list-style: none;
}

效果:
這裡寫圖片描述