php入門教程(十一)使用ajax打通前后端

ajax


ajax的好處是,當(dāng)我們執(zhí)行添加刪除或者更新數(shù)據(jù)的時(shí)候,頁面不會因?yàn)橥教D(zhuǎn)而刷新。還有一個(gè)好處就是,所有的請求都是通過異步url來獲取的,這就不得不提php的一個(gè)缺點(diǎn)—我們寫成php的時(shí)候,php只能被瀏覽器顯示。但是到了小程序里面,小程序無法識別php,只能寫成前后端分離的,這個(gè)時(shí)候,ajax的優(yōu)勢就顯現(xiàn)了出來。

我們來做一個(gè)例子感覺一下:


用戶管理demo

前端代碼:

這里我使用了jquery的ajax,注意,你的ajax參數(shù)中必須加上dataType:"json"這一項(xiàng),否則,你獲取來的數(shù)據(jù)有可能是一個(gè)string。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="https://cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
        <link rel="stylesheet" >
        <style>
            .regBox {
                width: 400px;
                margin: 0 auto;
                border: 1px solid #ccc;
                padding: 10px;
                background: bisque;
            }
            .regBox div,.regBox label{
                display: flex;
                font-weight: normal;
                padding: 5px 0;
            }
            .regBox span{
                display: inline-block;
                margin-right: 20px;
                width: 70px;
            }
            .regBox input[type=submit] {
                padding: 3px 30px;
                width: 300px;
            }
        </style>
    </head>
    <body>
        <div id="dataTable">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <td>id</td>
                        <td>用戶名</td>
                        <td>密碼</td>
                        <td>手機(jī)號</td>
                    </tr>
                </thead>
                <tbody id="main">
                </tbody>
            </table>
        </div>
        <div class="regBox">
            <h3>添加用戶</h3>
            郵箱:
            <!--注意你的input必須有name值 這個(gè)值就是url中?后面的值-->
            <input type="text" id="email" class="form-control">
            密碼:
            <input type="password" id="password" class="form-control">
            手機(jī)號:
            <input type="text" id="tel" class="form-control">
            <div>
                <button onclick="add()" class="btn btn-warning">提交</button>
            </div>
        </div>
        
        
        <script type="text/javascript">
            function query(){
                $.ajax({
                    type:"post",
                    dataType:"json", //這一句必須有
                    url:"curd.php",
                    data:{
                        "type":"query",
                    },
                    success:function(data){
                        //先清空節(jié)點(diǎn)內(nèi)容
                        $("#main").empty();
                        console.log(data);
                        for(var i=0;i<=data.length-1;i++){
                            $("#main").append("<tr>"+
                            "<td>"+data[i].id+"</td>"+
                            "<td>"+data[i].email+"</td>"+
                            "<td>"+data[i].password+"</td>"+
                            "<td>"+data[i].tel+"</td>"+
                            "</tr>");
                        }
                    }
                });
            }
            query();
            
            function add(){
                var email = $("#email").val();
                var password = $("#password").val();
                var tel = $("#tel").val();
                $.ajax({
                    type:"post",
                    dataType:"json", //這一句必須有
                    url:"curd.php",
                    data:{
                        "type":"add",
                        "email":email,
                        "password":password,
                        "tel":tel
                    },
                    success:function(data){
                        if(data=="1"){
                            alert("添加成功!")
                        }
                        //刷新一下內(nèi)容
                        query();
                    }
                });
            }
            
        </script>
    </body>
</html>

然后是后臺代碼:

1.config.php

<?php
    $con = mysqli_connect("127.0.0.1:3306","root","你的數(shù)據(jù)庫密碼","phptest");//連接數(shù)據(jù)庫服務(wù)
    mysqli_query($con,"set names 'utf8'"); //把連接方式設(shè)置為utf-8

2.curd.php

<?php
    require("config.php");
    //判斷查詢還是添加
    $type = $_POST["type"];
    if($type == "query"){
        $result = mysqli_query($con,"SELECT * FROM user"); //查詢所有記錄
        $contents = array();
        //循環(huán) 必須加,MYSQLI_ASSOC否則會返回?zé)o效數(shù)據(jù)
        while($rows = mysqli_fetch_array($result,MYSQLI_ASSOC)){
            $contents[] = $rows;
        }
        //print_r($contents);
        echo json_encode($contents);
    }
    //添加
    if($type == "add"){
        $val1 = $_POST["email"];
        $val2 = $_POST["password"];
        $val3 = $_POST["tel"];
        //使用mysqli_prepare防止用戶上傳sql語句來注入攻擊
        $stmt = mysqli_prepare($con,"insert into user (email,password,tel) VALUES (?, ?, ?)");
        mysqli_stmt_bind_param($stmt,"sss",$val1,$val2,$val3);
        mysqli_stmt_execute($stmt);
        if(mysqli_stmt_affected_rows($stmt)){
            echo 1;//成功返回1
        }else{
            echo 2;//不成功返回2
        }
    }

這樣就可以了。到了目前位置,你已經(jīng)學(xué)了會類的使用,存儲session,數(shù)據(jù)庫和如何通過ajax進(jìn)行前后端通訊。

其實(shí)php的基礎(chǔ)基本上就這些了。如果你想要深入了解,可以開始后續(xù)mvc框架學(xué)習(xí),加油吧!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Ajax的基本概念及使用 同步&異步 同步:必須等待前面的任務(wù)完成,才能繼續(xù)后面的任務(wù); 異步:不受當(dāng)前主要任務(wù)的...
    magic_pill閱讀 2,052評論 0 5
  • AJAX 原生js操作ajax 1.創(chuàng)建XMLHttpRequest對象 var xhr = new XMLHtt...
    碧玉含香閱讀 3,563評論 0 7
  • 1、PHP語言的一大優(yōu)勢是跨平臺,什么是跨平臺?一、PHP基礎(chǔ): PHP的運(yùn)行環(huán)境最優(yōu)搭配為Apache+MySQ...
    __書山有路__閱讀 1,612評論 0 15
  • Day 17/21 15+詹婷婷+杭州 【書籍名稱】《拖拉一點(diǎn)也無妨》 單看書名就覺得很有趣的一本書。在我們大喊著...
    小草莓_zhantt閱讀 294評論 0 0
  • 1 建立遠(yuǎn)程調(diào)試任務(wù) 2 在項(xiàng)目中的terminal命令行中 gradle assembleDebug -Dorg...
    Chauncey_Chen閱讀 2,240評論 4 4

友情鏈接更多精彩內(nèi)容