码迷,mamicode.com
首页 > Web开发 > 详细

js+php表格的增删改差

时间:2020-07-11 19:40:20      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:list   username   echo   open   服务   cas   send   inner   view   

js+php表格的增删改差

实现的效果如下图所示:
技术图片
{{uploading-image-727245.png(uploading...)}}

html基础页面

<    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">  
        <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
        <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
        <title>Document</title>
        <style>
            .box{
                box-sizing: border-box;
                width: 100%;
                height: 100%;
                padding: 100px;
                position: absolute;
                top: 0%;
                left: 0%;
                background-color: rgba(200, 200, 200, .7);
                display: none;
            }
            .panel-footer{
            display: flex;
            justify-content: center;
            align-items: center;
        }
        </style>

    </head>
    <body>
        <div class="container">
            <div class="panel panel-primary">
                 <div class="panel-heading">
                     <h2>学生成绩管理系统</h2>
                 </div>
                 <div class="panel-body">
                    <button type="button" class="btn btn-success select">获取学生成绩</button>
                    <button type="button" class="btn btn-success add">添加学生成绩</button>
                     <table class="table table-hover">
                         <thead>
                             <tr>
                                 <th>学生学号</th>
                                 <th>学生姓名</th>
                                 <th>语文成绩</th>
                                 <th>数学成绩</th>
                                 <th>英语成绩</th>
                                 <th colspan="2" style="text-align: center;">操作</th>
                             </tr>
                         </thead>
                         <tbody id="tb"> </tbody>
                     </table>
                 </div>
                 <div class=‘panel-footer‘>
                    <nav aria-label="...">
                        <ul class="pager">
                          <li class="previous disabled"><a href="#"><span aria-hidden="true">&larr;</span> 上一页</a></li>
                        </ul>
                    </nav>
                    <nav aria-label="Page navigation">
                        <ul class="pagination">
                          <li class = ‘active‘><a href="#">1</a></li>
                          <li><a href="#">2</a></li>
                          <li><a href="#">3</a></li>
                          <li><a href="#">4</a></li>
                          <li><a href="#">5</a></li>
                        </ul>
                    </nav>
                    <nav aria-label="...">
                        <ul class="pager">  
                          <li class="next"><a href="#">下一页 <span aria-hidden="true">&rarr;</span></a></li>
                        </ul>
                    </nav>
                </div>
            </div>
        </div>

        <div class=‘panel-body box‘>
            <div class=‘form-group‘>
                <label for="username">学生姓名:</label>
                <input type="text" class=‘form-control‘ name=‘username‘ id="username" placeholder="学生姓名">
            </div>
            <div class=‘form-group‘>
                <label for="chinese">语文成绩:</label>
                <input type="text" class=‘form-control‘ name=‘chinese‘ placeholder="语文成绩">
            </div>
            <div class=‘form-group‘>
                <label for="math">数学成绩:</label>
                <input type="text" class=‘form-control‘ name=‘math‘ placeholder="数学成绩">
            </div>
            <div class=‘form-group‘>
                <label for="english">英语成绩:</label>
                <input type="text" class=‘form-control‘ name=‘english‘ placeholder="英语成绩">
            </div>
            <button id = ‘btn1‘ class = ‘btn btn-primary cancel‘>取消</button>
            <button id = ‘submit‘ class = ‘btn btn-primary‘>确定</button>
        </div>
    </body>
    <script type="module">
        import {post} from "./ajax.js";
        var oBtain = document.querySelector(".select");
        var oAdd = document.querySelector(".add")
        var oTb = document.querySelector("#tb");
        var oBox = document.querySelector(".box");
        var oCancel =document.querySelector(".cancel");
        var oSubmit = document.getElementById("submit");

        //展示信息
        function show(){
            post({
            url:"show.php",
            success:function(result){
                var arr = JSON.parse(result);
                var str = ‘‘;
                for(var i = 0;i<arr.length;i++){
                    str +=`<tr>
                        <td>${arr[i].id}</td>
                        <td>${arr[i].username}</td>
                        <td>${arr[i].chinese}</td>
                        <td>${arr[i].math}</td>
                        <td>${arr[i].english}</td>
                        <td ><button type="button" class="btn btn-danger" id=‘${arr[i].id}‘>删除</button></td>
                        <td><button type="button" class="btn btn-warning" id=‘${arr[i].id}‘>修改</button></td>
                        </tr>`
                }
                oTb.innerHTML=str;
            },
            error:function(error){
                console.log(error)
            }
        })
        }
        oBtain.onclick = function(){
           show()
        }

        var aIput = document.querySelectorAll("input");
        //插入信息
        oAdd.onclick = function(){
            oBox.style.display="block";
            oSubmit.onclick = function(){
                post({
                url:"insert.php",
                data:{
                    username:aIput[0].value,
                    chinese:aIput[1].value,
                    math:aIput[2].value,
                    english:aIput[3].value,
                },
                success:function(result){
                    if(result=="success"){
                        alert("添加成功")
                    }else{
                        alert("添加失败,请重试")
                    }
                    
                },
                error:function(error){
                    console.log(error)
                }
                })
        }
    }
    oCancel.onclick = function(){
                oBox.style.display="none";
    }

    //删除和修改学生信息
    oTb.onclick = function(eve){
        var e = eve||window.event;
        var target = e.target ||e.srcElement;
        if(target.nodeName.toLocaleLowerCase() == ‘button‘){
            switch(target.className){
                //删除
                case ‘btn btn-danger‘:                
                    post({
                        url:"delete.php",
                        data:{
                            id:target.id
                        },
                    success:function(result){
                        if(result=="success"){
                            oTb.removeChild(target.parentNode.parentNode);
                            alert("删除成功")
                        }else{
                            alert("删除失败")
                        }
                        }
                    });
                    break;
                    //修改
                case ‘btn btn-warning‘:
                post({
                    url:"update.php",
                    data:{
                            id:target.id
                        },
                    success:function(result){
                        var arr = JSON.parse(result);
                        oBox.style.display="block";
                            aIput[0].value=arr[0].username,
                            aIput[1].value=arr[0].chinese,
                            aIput[2].value=arr[0].math,
                            aIput[3].value=arr[0].english;
                            var id = arr[0].id;
                            oSubmit.onclick=function(){
                                post({
                            url:"update1.php",
                                data:{
                                    id:id,
                                    username:aIput[0].value,
                                    chinese:aIput[1].value,
                                    math:aIput[2].value,
                                    english:aIput[3].value,
                                },
                                success:function(result){
                                    if(result=="success"){
                                        alert("修改成功")
                                    }else{
                                        alert("请重新修改")
                                    }
                                }
                      })
                            }

                        }
                })
               
            }       
    }
 }
    </script>
    </html>

通过ajax传数据-ajax.js

export{
    post,
    get,
    ajax
}

function post(){
    var argus =Object.assign({"method" :"post"},...arguments)
    var g = new Ajax(argus);
    g.init();
    g.type()
}

function get(){
    var argus =Object.assign({"method" :"get"},...arguments)
    var g = new Ajax(argus);
    g.init();
    g.type()
}

// function ajax(){
//     var a =new Ajax(...arguments);
//     a.init();
//     a.type();
// }

function ajax(){
    var a = new Ajax(...arguments);
    a.init();
    a.type()
}
class Ajax{
    constructor({method,url,data,success,error}){
        this.method = method;
        this.url = url;
        this.data = data;
        this.success = success;
        this.error = error;
    }
    init(){
        var xhr = null;
        try{
            xhr = new  XMLHttpRequest;
        }catch{
            xhr = new ActiveXObject("XMLHTTP");
        }
        return xhr;
    }

    type(){
        var xhr= this.init()
        var querystring=""
        if(this.data){
            querystring = this.queryString(this.data);
        }
        if(this.method=="get"){
            xhr.open(this.method,this.url+"?"+querystring,true);
            xhr.send();
        }else{
            xhr.open(this.method,this.url,true);
            xhr.setRequestHeader(‘content-type‘, "application/x-www-form-urlencoded");
            xhr.send(querystring);
        }

        xhr.onreadystatechange = ()=>{
            if(xhr.readyState ==4){
                if(xhr.status==200){
                    if(this.success){
                        this.success(xhr.responseText)
                    }
                }else{
                    if(this.error){
                        this.error("error"+xhr.status)
                    }
                }
            }
           
        }
    }

    queryString(dataObj){
        var str=‘‘;
        for(var attr in dataObj){
            str+=`${attr}=${dataObj[attr]}&`
        }
        return str.substring(0,str.length-1)
    }
}

分页-paging.php

<?php
header("content-type:text/html,charset=‘utf8‘");
$page = $_POST[‘page‘] ? $_POST[‘page‘] :1;
$limit = $_POST[‘limit‘] ? $_POST[‘limit‘]:10;
$count = 0; //总条数
$pages = 0; //总页数
$skip = 0; //跳过的条数

$link=mysqli_connect("localhost","root","root");
if(!$link){
    echo "服务器忙,请重试";
    exit;
}
mysqli_set_charset($link,"utf8");
mysqli_select_db($link,"nz");
$sql = "SELECT COUNT(*) FROM students";
$res=mysqli_query($link,$sql);
$row = mysqli_fetch_assoc($res);
$count = $row[‘COUNT(*)‘];
// echo $count;
$pages = ceil($count / $limit);
$page = max(1, $page);
$page = min($page, $pages);
$skip = ($page -1) * $limit;
$msg =array(
    "page" => $page, 
    "count" => $count, 
    "pages" => $pages, 
    "limit" => $limit, 
    "skip" => $skip,
    "userlist" => array()
);
$sql2 = "SELECT * FROM students LIMIT {$skip}, {$limit}";
$res2 = mysqli_query($link, $sql2);
while($row2 = mysqli_fetch_assoc($res2)){
    array_push($msg[‘userlist‘], $row2);
}
echo json_encode($msg);
mysqli_close($link);

?>

数据添加 insert.php

<?php

header("content-type:text/html,charset=‘utf8‘");
$username = $_POST[‘username‘];
$chinese = $_POST[‘chinese‘];
$math = $_POST[‘math‘];
$english = $_POST[‘english‘];
$link = mysqli_connect("localhost","root","root");
if(!$link){
    echo "服务器忙,请稍后重试";
    exit;
};
mysqli_set_charset($link,"utf8");
mysqli_select_db($link,"nz");
$sql ="insert into students (username,chinese,math,english) values(‘{$username}‘,‘{$chinese}‘,‘{$math}‘,‘{$english}‘)";
$res = mysqli_query($link,$sql);
if($res){
    echo "success";
}else{
    echo "error";
};

mysqli_close($link);
?>

数据删除 delete.php

<?php
header(‘content-type:text/html,charset="utf8"‘);
$id=$_POST[‘id‘];
$link=mysqli_connect("localhost","root","root");
if(!$link){
    echo "服务器忙,请重试";
    exit;
};
mysqli_set_charset($link,"utf8");
mysqli_select_db($link,"nz");
$sql="delete from students where id={$id}";
$res =  mysqli_query($link,$sql);
if($res){
    echo "success";
}else{
    echo "error";
};
mysqli_close($link);
?>

数据修改-查找update.php

<?php
header("content-type:text/html,charset=‘utf8‘");
$id=$_POST[‘id‘];

$link=mysqli_connect("localhost","root","root");
if(!$link){
    echo "服务器忙,请重试";
    exit;
}
mysqli_set_charset($link,"utf8");
mysqli_select_db($link,"nz");
$sql="select  * from students where id =‘{$id}‘";
$res=mysqli_query($link,$sql);
$arr = array();
while($row=mysqli_fetch_assoc($res)){
    array_push($arr,$row);
};
echo json_encode($arr);
mysqli_close($link);

?>

数据修改-更新 update1.php

<?php
header("content-type:text/html,charset=‘utf8‘");
$id = $_POST[‘id‘];
$username = $_POST[‘username‘];
$chinese = $_POST[‘chinese‘];
$math = $_POST[‘math‘];
$english = $_POST[‘english‘];

$link=mysqli_connect("localhost","root","root");
if(!$link){
    echo "服务器忙,请重试";
    exit;
}
mysqli_set_charset($link,"utf8");
mysqli_select_db($link,"nz");
// $sql="delete from students where id={$id}";
$sql = "UPDATE students SET username ={$username} ,chinese ={$chinese},math={$math},english={$english} where id={$id}";
$res=mysqli_query($link,$sql);
if($res){
    echo "success";
}else{
    echo "error";
};
mysqli_close($link);

?>

js+php表格的增删改差

标签:list   username   echo   open   服务   cas   send   inner   view   

原文地址:https://www.cnblogs.com/cupid10/p/13284473.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!