美文网首页php入门教程—打通前后端
php入门教程(十一)使用ajax打通前后端

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

作者: 党云龙 | 来源:发表于2019-10-28 15:25 被阅读0次

    ajax


    ajax的好处是,当我们执行添加删除或者更新数据的时候,页面不会因为同步跳转而刷新。还有一个好处就是,所有的请求都是通过异步url来获取的,这就不得不提php的一个缺点—我们写成php的时候,php只能被浏览器显示。但是到了小程序里面,小程序无法识别php,只能写成前后端分离的,这个时候,ajax的优势就显现了出来。

    我们来做一个例子感觉一下:


    用户管理demo

    前端代码:

    这里我使用了jquery的ajax,注意,你的ajax参数中必须加上dataType:"json"这一项,否则,你获取来的数据有可能是一个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" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            <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>手机号</td>
                        </tr>
                    </thead>
                    <tbody id="main">
                    </tbody>
                </table>
            </div>
            <div class="regBox">
                <h3>添加用户</h3>
                邮箱:
                <!--注意你的input必须有name值 这个值就是url中?后面的值-->
                <input type="text" id="email" class="form-control">
                密码:
                <input type="password" id="password" class="form-control">
                手机号:
                <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){
                            //先清空节点内容
                            $("#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("添加成功!")
                            }
                            //刷新一下内容
                            query();
                        }
                    });
                }
                
            </script>
        </body>
    </html>
    

    然后是后台代码:

    1.config.php

    <?php
        $con = mysqli_connect("127.0.0.1:3306","root","你的数据库密码","phptest");//连接数据库服务
        mysqli_query($con,"set names 'utf8'"); //把连接方式设置为utf-8
    

    2.curd.php

    <?php
        require("config.php");
        //判断查询还是添加
        $type = $_POST["type"];
        if($type == "query"){
            $result = mysqli_query($con,"SELECT * FROM user"); //查询所有记录
            $contents = array();
            //循环 必须加,MYSQLI_ASSOC否则会返回无效数据
            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
            }
        }
    

    这样就可以了。到了目前位置,你已经学了会类的使用,存储session,数据库和如何通过ajax进行前后端通讯。

    其实php的基础基本上就这些了。如果你想要深入了解,可以开始后续mvc框架学习,加油吧!

    相关文章

      网友评论

        本文标题:php入门教程(十一)使用ajax打通前后端

        本文链接:https://www.haomeiwen.com/subject/eqsbvctx.html