6.15ajax写数据库的增删改查

Posted sun1987

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了6.15ajax写数据库的增删改查相关的知识,希望对你有一定的参考价值。

<!--<!DOCTYPE html>-->
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" type="text/css" href="public/bootstrap/css/bootstrap.min.css">
    <script src="public/jquery/jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="public/bootstrap/js/bootstrap.min.js" type="text/javascript" charset="utf-8"></script>
    <title>Document</title>
    <style type="text/css">
        .add{
            width: 100px;
            height: 30px;
            background-color: #117A8B;
            border-radius: 3px;
            text-align: center;
            line-height: 30px;
            color: white;
        }
        .add:hover{
            cursor: pointer;
        }
        .plsc{
            width: 100px;
            height: 30px;
            background-color: #117A8B;
            border-radius: 3px;
            text-align: center;
            line-height: 30px;
            color: white;
        }
        .plsc:hover{
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="add" data-toggle="modal"  data-target="#myModal">添加 </div>
    <form class="form-inline">
        <label for="name">姓名:</label>
        <input type="text" class="form-control" id="name" placeholder="请输入查询的姓名" >
        <label for="banji">班级:</label>
        <input type="text" class="form-control" id="banji" placeholder="请输入查询的班级">
        <div class="add" onclick="selectData()">查询</div>                
    </form>    
    
    <table class="table" border="1" cellspacing="0" cellpadding="0">
        
    </table>
    <span onclick=\'pldelete()\' class="plsc">批量删除</span>
    
    <!--======================添加模态框================-->
    <!-- 模态框 -->
<div class="modal fade" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">
 
      <!-- 模态框头部 -->
      <div class="modal-header">
        <h4 class="modal-title">添加页面</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
 
      <!-- 模态框主体 -->
      <div class="modal-body">
      <form>
          <div class="form-group">
              <label for="xuh">序号:</label>
              <input type="text" class="form-control" id="xuh">
          </div>
          <div class="form-group">
              <label for="xh">学号:</label>
              <input type="text" class="form-control" id="xh">
          </div>
          <div class="form-group">
              <label for="xm">姓名:</label>
              <input type="text" class="form-control" id="xm">
          </div>
          <div class="form-group">
              <label for="xb">性别:</label>
              <input type="text" class="form-control" id="xb">
          </div>
          <div class="form-group">
              <label for="sr">出生日期:</label>
              <input type="text" class="form-control" id="sr">
          </div>
          <div class="form-group">
              <label for="bj">班级:</label>
              <input type="text" class="form-control" id="bj">
          </div>
          
      </form>
      </div>
 
      <!-- 模态框底部 -->
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="add()">添加</button>
      </div>
 
    </div>
  </div>
 </div>
<!--======================修改模态框================-->
    <!-- 模态框 -->
<div class="modal fade" id="xiugaiModal">
  <div class="modal-dialog">
    <div class="modal-content">
 
      <!-- 模态框头部 -->
      <div class="modal-header">
        <h4 class="modal-title">修改页面</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
 
      <!-- 模态框主体 -->
      <div class="modal-body">
      <form>
          <div class="form-group">
              <label for="xuh">序号:</label>
              <input type="text" class="form-control" id="xuh1">
          </div>
          <div class="form-group">
              <label for="xh">学号:</label>
              <input type="text" class="form-control" id="xh1">
          </div>
          <div class="form-group">
              <label for="xm">姓名:</label>
              <input type="text" class="form-control" id="xm1">
          </div>
          <div class="form-group">
              <label for="xb">性别:</label>
              <input type="text" class="form-control" id="xb1">
          </div>
          <div class="form-group">
              <label for="sr">出生日期:</label>
              <input type="text" class="form-control" id="sr1">
          </div>
          <div class="form-group">
              <label for="bj">班级:</label>
              <input type="text" class="form-control" id="bj1">
          </div>
          
      </form>
      </div>
 
      <!-- 模态框底部 -->
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="modify()">修改</button>
      </div>
 
    </div>
  </div>
 </div>
</body>
</html>
<script type="text/javascript">
    var tab = document.getElementsByTagName("table")[0];
    var colorattr = ["table-primary","table-success","table-danger","table-info","table-warning","table-active","table-secondary"];
    loadData(\'\',\'\');
    
    function selectData(){
        var name = document.getElementById("name").value;
        var banji = document.getElementById("banji").value;
        loadData(name,banji);
    }
    
    function loadData(a,b){
            $.ajax({
            type:"post",
            url:"chuli.php",
            async:true,
            data:{
                "type":"chaxun",
                "name":a,
                "banji":b
            },
            dataType:"json",//可以返回数组
            success:function(data){
                var str="";
                str +="<tr><td>全选<input type=\'checkbox\' onclick=\'qx(this)\'/></td><td>序号</td><td>学号</td><td>姓名</td><td>性别</td><td>出生日期</td><td>班级</td><td>操作</td></tr>";
                for(var i= 0;i<data.length;i++){
                    str +="<tr class = "+colorattr[i]+">";
                    str +="<td><input class=\'ckinput\' type=\'checkbox\' value=\'"+data[i][0]+"\' /></td>";
                                                               //+的作用跟PHP里的{}一样,不拼上+识别不了
                    for(var j = 0;j<data[i].length;j++){
                        str +="<td>"+data[i][j]+"</td>";
                    }
                    str +="<td><button type=\'button\' class=\'btn btn-primary\' data-toggle=\'modal\' data-target=\'#xiugaiModal\' onclick =\'add_modify(\\""+data[i]+"\\")\'>修改</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\'button\' class=\'btn btn-info\' onclick =\'deleteData(\\""+data[i][0]+"\\")\'>删除</button></td>";
                    str+="</tr>";                                                                                                            //括号里传的是数组的每一项的值属于字符串;        
                }
                tab.innerHTML = str;
            }
            
         });
    }
    function add(){
        var xuh = document.getElementById("xuh").value;
        var xh = document.getElementById("xh").value;
        var xm = document.getElementById("xm").value;
        var xb = document.getElementById("xb").value;
        var sr = document.getElementById("sr").value;
        var bj = document.getElementById("bj").value;
        $.ajax({
            type:"post",
            url:"chuli.php",
            async:true,
            data:{
                "type":"tianjia",
                "xuh":xuh,
                "xh":xh,
                "xm":xm,
                "xb":xb,
                "sr":sr,
                "bj":bj
    
            },
            dataType:"text",
            success:function(data){
                if(data.trim() == "ok"){//php返回的data带有空格需要加trim()去掉两头的空格
                    alert("添加成功!");
                    loadData(\'\',\'\');//重新加载页面
                }
            }
        });
    }
    function add_modify(at){
        var attr = at.split(",");
         //[ "6", "109", "王芳", "女", "1975-02-10 00:00:00", "95031" ]
         //"2:3:4:5".split(":")    //将返回["2", "3", "4", "5"]
         //"|a|b|c".split("|")    //将返回["", "a", "b", "c"] 
        var attr_id = ["xuh1","xh1","xm1","xb1","sr1","bj1"];
        for(var i=0;i<attr.length;i++){
            document.getElementById(attr_id[i]).value = attr[i];
        }
    }
    function modify(){
        var xuh1 = document.getElementById("xuh1").value;
        var xh1 = document.getElementById("xh1").value;
        var xm1 = document.getElementById("xm1").value;
        var xb1 = document.getElementById("xb1").value;
        var sr1 = document.getElementById("sr1").value;
        var bj1 = document.getElementById("bj1").value;
        $.ajax({
            type:"post",
            url:"chuli.php",
            async:true,
            data:{
                "type":"xiugai",
                "xuh1":xuh1,
                "xh1":xh1,
                "xm1":xm1,
                "xb1":xb1,
                "sr1":sr1,
                "bj1":bj1
            },
            dataType:"text",
            success:function(data){
                if(data.trim() == "ok"){
                    alert("修改成功!");
                    loadData(\'\',\'\');
                }
            }
        });
    }
    function deleteData(id){
        $.ajax({
            type:"post",
            url:"chuli.php",
            async:true,
            data:{
                "type":"shanchu",
                "id":id
            },
            dataType:"text",
            success:function(data){
                if(data.trim() == "ok"){
                    alert("删除成功!");
                    loadData(\'\',\'\');
                }
            }
        });
    }
    function qx(t){
        var ckinput = document.getElementsByClassName("ckinput");
        for(var i=0;i<ckinput.length;i++){
            if(t.checked){
                ckinput[i].checked = true;    
            }else{
                ckinput[i].checked = false;
            }
        }
    }
    function pldelete(){
        
        var ckinput = document.getElementsByClassName("ckinput");
        var str = "";
        var bs = 0;
        for(var i=0;i<ckinput.length;i++){
            if(ckinput[i].checked){
                bs++;//判断复选框有没有选中;
                str +=ckinput[i].value+"\',\'";
            }
        }
        
        if(bs==0){
            alert("至少选择一项");
        }else{
             // 输出12\',\'34\',\'需要去掉后三位
        str = str.substr(0,str.length-3);
        
        $.ajax({
            type:"post",
            url:"chuli.php",
            async:true,
            data:{
                "type":"plshanchu",
                "str":str
            },
            dataType:"text",
            success:function(data){
                if(data.trim() == "ok"){
                    alert("批量删除成功!");
                    loadData(\'\',\'\');
                }
            }
        });
        }
        
    }
</script>

主页


<?php
 //Get是用来从服务器上获得数据,而Post是用来向服务器上传递数据。
   header("Content-type: text/html; charset=utf-8");
   $type = $_POST[\'type\'];
   $conn = new mysqli("localhost","root","","ceshi");
   $conn->connect_error?die("链接失败"):"";
 
 switch($type){
    case "chaxun":
    $name = $_POST[\'name\'];
    $banji = $_POST[\'banji\'];
    $sql = "select * from student where sname like \'%{$name}%\' and class like \'%{$banji}%\'";
    $result = $conn->query($sql);
    $attr = $result->fetch_all();
    echo json_encode($attr);
  break;
  case "tianjia":
    $xuh = $_POST[\'xuh\'];
    $xh = $_POST[\'xh\'];
    $xm = $_POST[\'xm\'];
    $xb = $_POST[\'xb\'];
    $sr = $_POST[\'sr\'];
    $bj = $_POST[\'bj\'];
    $sql = "insert into student values(\'{$xuh}\',\'{$xh}\',\'{$xm}\',\'{$xb}\',\'{$sr}\',\'{$bj}\')";
    if($result=$conn->query($sql)){
      echo "ok";
    }
  break;
  case "xiugai":
    $xuh1 = $_POST[\'xuh1\'];
    $xh1 = $_POST[\'xh1\'];
    $xm1 = $_POST[\'xm1\'];
    $xb1 = $_POST[\'xb1\'];
    $sr1 = $_POST[\'sr1\'];
    $bj1 = $_POST[\'bj1\'];
    $sql = "update student set sno=\'{$xh1}\',sname = \'{$xm1}\',ssex = \'{$xb1}\',sbirthday = \'{$sr1}\',class = \'{$bj1}\' where id =\'{$xuh1}\'";
    if($result=$conn->query($sql)){
      echo "ok";
    }
  break;
  case "shanchu":
    $id= $_POST[\'id\'];
    $sql = "delete from student where id = \'{$id}\'";
    if($result=$conn->query($sql)){
      echo "ok";
    }
  break;
  case "plshanchu":
    $str = $_POST[\'str\'];
    $sql = "delete from student where id in (\'{$str}\')";
    if($result=$conn->query($sql)){
      echo "ok";
    }
  break;
   
   }
 
 
 
 


?>


php页

 

以上是关于6.15ajax写数据库的增删改查的主要内容,如果未能解决你的问题,请参考以下文章

ssm表格形式的增删改查点击修改按钮获取修改时间

数据的增删改查(三层)

求用jquery实现简单的增删改查,不要求界面,最好是增删改查各用一个js文件写,使用框架不限,上传项目

SQL的增删改查

【JPA】联表的增删改查(一)many to many

JavaWeb 增删改查功能