2.data.php
3.crud.sql

相關(guān)學(xué)習(xí)推薦:PHP編程從入門到精通

數(shù)據(jù)交互實(shí)現(xiàn)1:查詢

1.mysql 數(shù)據(jù)庫建表
2.php查詢接口
3.前端數(shù)據(jù)展現(xiàn)

mysql 數(shù)據(jù)庫建表

數(shù)據(jù)庫名稱:crud第一個(gè)表名:t_users主鍵:user_id,自增長(zhǎng)排列

<?php
  //測(cè)試php是否可以拿到數(shù)據(jù)庫中的數(shù)據(jù)
  /*echo "44444";*/
  
  //做個(gè)路由 action為url中的參數(shù)
  $action = $_GET['action'];

  switch($action) {
    case 'init_data_list':
      init_data_list();
      break;
    case 'add_row':
      add_row();
      break;
    case 'del_row':
      del_row();
      break;
    case 'edit_row':
      edit_row();
      break;
  }
  
  //查詢方法
  function init_data_list(){
    //測(cè)試 運(yùn)行crud.html時(shí)是否可以獲取到 下面這個(gè)字符串
    /*echo "46545465465456465";*/
    
    //查詢表
    $sql = "SELECT * FROM `t_users`";
    $query = query_sql($sql);
    while($row = $query->fetch_assoc()){
      $data[] = $row;
    }
    
    $json = json_encode(array(
      "resultCode"=>200,
      "message"=>"查詢成功!",
      "data"=>$data
    ),JSON_UNESCAPED_UNICODE);
    
    //轉(zhuǎn)換成字符串JSON
    echo($json);
  }
  
  
  /**查詢服務(wù)器中的數(shù)據(jù)
   * 1、連接數(shù)據(jù)庫,參數(shù)分別為 服務(wù)器地址 / 用戶名 / 密碼 / 數(shù)據(jù)庫名稱
   * 2、返回一個(gè)包含參數(shù)列表的數(shù)組
   * 3、遍歷$sqls這個(gè)數(shù)組,并把返回的值賦值給 $s
   * 4、執(zhí)行一條mysql的查詢語句
   * 5、關(guān)閉數(shù)據(jù)庫
   * 6、返回執(zhí)行后的數(shù)據(jù)
   */
  function query_sql(){
    $mysqli = new mysqli("127.0.0.1", "root", "root", "crud");
    $sqls = func_get_args();
    foreach($sqls as $s){
      $query = $mysqli->query($s);
    }
    $mysqli->close();
    return $query;
  }
?>

前端實(shí)現(xiàn):

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.css" rel="external nofollow" >
    <!-- jQuery -->
    <script type="text/javascript" src="http://code.changer.hk/jquery/1.11.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://code.changer.hk/jquery/plugins/jquery.cookie.js"></script>
    <!-- bootstrap-table -->
    <link rel="stylesheet" href="http://code.changer.hk/bootstrap-table/1.6.0/bootstrap-table.min.css" rel="external nofollow" >
    <script type="text/javascript" src="http://code.changer.hk/bootstrap-table/1.6.0/bootstrap-table.min.js"></script>
    <style type="text/css">
      #table {
        padding: 0;
      }
      
      #table>tbody>tr {
        cursor: pointer;
      }
      
      #table>tbody>tr>td.bs-checkbox {
        vertical-align: middle;
      }
    </style>
    <title>增刪改查</title>
  </head>

  <body style="padding: 50px;">
    <p class="toolbar1" style="margin-bottom: -43px;">
      <button id="remove" class="btn btn-danger" disabled>刪除</button>
      <button class="btn btn-primary" id="btn">新建</button>
    </p>
    <p id="table"></p>

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <!-- Latest compiled and minified JavaScript -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.js"></script>
    <!-- Latest compiled and minified Locales -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/locale/bootstrap-table-zh-CN.min.js"></script>
    <script type="text/javascript">
      var $table = $('#table'),
        $remove = $('#remove');

      $(function() {
        searchData();
      });

      function prepareDisplayData(data) {
        return {
          total: data.data.length,
          fixedScroll: false,
          rows: data.data
        };
      }

      function searchData() {
        var search_url = "./php/data.php";

        //url 中問號(hào)后面的參數(shù) action,這個(gè)對(duì)象就是查詢的參數(shù)
        var dataParam = {
          action: "init_data_list"
        };

        $.ajax({
          type: "get",
          url: search_url,
          data: dataParam,
          dataType: 'json',
          contentType: 'application/json; charset=utf-8',
          success: function(data) {
            //測(cè)試是否可以拿到php中的數(shù)據(jù)
            console.log(data);
            //遍歷這個(gè)數(shù)組
            if(data.resultCode == 200) {
              var itemArr = data.data;
              for(var i = 0; i < itemArr.length; i  ) {
                var item = itemArr[i];
                console.log(item);
              }
            }

            //bootstrap-table 組織數(shù)據(jù)
            var displayData = prepareDisplayData(data);
            if(displayData.total > 0) {
              $('#table').bootstrapTable('load', displayData);
            } else {
              console.log("last page or empty.");
            }
          },
          error: function(data) {
            alert('服務(wù)器出錯(cuò)');
          },
        });
      }

      $('#table').bootstrapTable({
        pagination: true,
        sidePagination: 'server', //設(shè)置為服務(wù)器端分頁
        pageNumber: 1,
        pageSize: 10,
        pageList: [10, 20, 50, 100],
        search: true,
        showColumns: true,
        showRefresh: true,
        columns: [{
          field: 'state',
          checkbox: true,
        }, {
          field: 'user_id',
          title: '用戶Id',
          width: '50',
          align: 'center',
          valign: 'middle'
        }, {
          field: 'user_name',
          title: '用戶名稱',
          width: '500',
          align: 'center',
          valign: 'middle'
        }, {
          field: 'user_age',
          title: '用戶年齡',
          width: '500',
          align: 'center',
          valign: 'middle'
        }, {
          field: 'user_sex',
          title: '用戶性別',
          width: '500',
          align: 'center',
          valign: 'middle'
        }, {
          field: 'user_add',
          title: '編輯',
          formatter: forwardFormatter,
          width: '500',
          align: 'center',
          valign: 'middle'
        }]
      }).on('page-change.bs.table', function(e, page, size) {
        fillData();
      }).on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function() {
        var tes = !$table.bootstrapTable('getSelections').length
        $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);
      });

      
      function forwardFormatter(value, row, index) {
        var value = "修改";
        return "<a href='#/"   row.user_id   "' class='btn btn-link'>"   value   "</a>";
      }
    </script>
  </body>
</html>

實(shí)現(xiàn)效果:

<?php
  //測(cè)試php是否可以拿到數(shù)據(jù)庫中的數(shù)據(jù)
  /*echo "44444";*/
  
  //做個(gè)路由 action為url中的參數(shù)
  $action = $_GET['action'];

  switch($action) {
    case 'init_data_list':
      init_data_list();
      break;
    case 'add_row':
      add_row();
      break;
    case 'del_row':
      del_row();
      break;
    case 'edit_row':
      edit_row();
      break;
  }

//刪除方法
  function del_row(){
    //測(cè)試
    /*echo "ok!";*/
    
    //接收傳回的參數(shù)
    $rowId = $_GET['rowId'];
    $sql = "delete from t_users where user_id='$rowId'";
    
    if(query_sql($sql)){
      echo "ok!";
    }else{
      echo "刪除失?。?quot;;
    }
  }
?>

前端實(shí)現(xiàn)JS部分:

var $table = $('#table'),
  $remove = $('#remove');

  $(function() {
    delData();
  });

function delData() {
        $remove.on('click', function() {
          if(confirm("是否繼續(xù)刪除")) {
            var rows = $.map($table.bootstrapTable('getSelections'), function(row) {
              //返回選中的行的索引號(hào)
              return row.user_id;
            });
          }
          
          $.map($table.bootstrapTable('getSelections'),function(row){
            var del_url = "./php/data.php";
            //根據(jù)userId刪除數(shù)據(jù),因?yàn)檫@個(gè)id就是 傳給服務(wù)器的參數(shù)
            var rowId = row.user_id;
            
            $.ajax({
              type:"delete",
              url:del_url   "?action=del_row&rowId="   rowId,
              dataType:"html",
              contentType: 'application/json;charset=utf-8',
              success: function(data) {
                $table.bootstrapTable('remove',{
                  field: 'user_id',
                  values: rows
                });
                $remove.prop('disabled', true);
              },
              error:function(data){
                alert('刪除失??!');
              }
            });
          });
        })
      }

調(diào)試方法:

數(shù)據(jù)交互實(shí)現(xiàn)3:新增

在寫php的方法上,我覺得我的方法是有問題的,因?yàn)樗械膮?shù),也就是所有的需要新增的數(shù)據(jù)都是通過 接口以 ? 后跟參數(shù)的方式添加成功的。功能是可以實(shí)現(xiàn),但是如果新增的數(shù)據(jù)較大,這個(gè)方法顯示是不可行的,但是還沒有找到合適的方法,煩請(qǐng)大俠們指點(diǎn)。

php:

<?php
  //測(cè)試php是否可以拿到數(shù)據(jù)庫中的數(shù)據(jù)
  /*echo "44444";*/
  
  //做個(gè)路由 action為url中的參數(shù)
  $action = $_GET['action'];

  switch($action) {
    case 'init_data_list':
      init_data_list();
      break;
    case 'add_row':
      add_row();
      break;
    case 'del_row':
      del_row();
      break;
    case 'edit_row':
      edit_row();
      break;
  }

//新增方法
  function add_row(){
    /*獲取從客戶端傳過來的數(shù)據(jù)*/
    $userName = $_GET['user_name'];
    $userAge = $_GET['user_age'];
    $userSex = $_GET['user_sex'];
    //INSERT INTO 表名 (列名1,列名2,...)VALUES ('對(duì)應(yīng)的數(shù)據(jù)1','對(duì)應(yīng)的數(shù)據(jù)2',...)
    // VALUES 的值全為字符串,因?yàn)楸韺傩栽O(shè)置為字符串
    $sql = "INSERT INTO t_users (user_name,user_age,user_sex) VALUES ('$userName','$userAge','$userSex')";
    if(query_sql($sql)){
      echo "ok!";
    }else{
      echo "新增成功!";
    }
  }

  function query_sql(){
    $mysqli = new mysqli("127.0.0.1", "root", "root", "crud");
    $sqls = func_get_args();
    foreach($sqls as $s){
      $query = $mysqli->query($s);
    }
    $mysqli->close();
    return $query;
  }
?>

前端實(shí)現(xiàn)JS部分:

html使用了bootstrap 的 modal作為新增時(shí)的彈出框

<!--新增彈框-->
    <p class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
      <p class="modal-dialog" role="document">
        <p class="modal-content">
          <p class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="exampleModalLabel">用戶新增</h4>
          </p>
          <p class="modal-body">
            <form id="listForm" method="post">
              <p class="form-group">
                <label for="userName" class="control-label">用戶名稱</label>
                <input type="text" class="form-control" id="userName">
              </p>
              <p class="form-group">
                <label for="userAge" class="control-label">用戶年齡</label>
                <input type="text" class="form-control" id="userAge">
              </p>
              <p class="form-group">
                <label class="control-label" for="user-sex">用戶性別</label>
                <p class="">
                  <select id="user-sex" class="form-control" name="user-sex" style="width: 100%" >
                    <option value='-1'>請(qǐng)選擇</option>
                    <option value='0'>男</option>
                    <option value='1'>女</option>
                  </select>
                </p>
              </p>
            </form>
          </p>
          <p class="modal-footer">
            <button id="close" type="button" class="btn btn-default" data-dismiss="modal">關(guān)閉</button>
            <button id="save" type="button" class="btn btn-primary">保存</button>
          </p>
        </p>
      </p>
    </p>
var $table = $('#table'),
   $remove = $('#remove');

  $(function() {
      searchData();
    delData();
        
    $('#save').click(function(){
      addData();
    });
  }); 
function addData(){
        var userName = $('#userName').val();
        var userAge = $("#userAge").val();
        var userSex = $('#user-sex').val() == '0' ? '男' : '女';
        
        var addUrl = "./php/data.php?action=add_row&user_name="   userName   "&user_age="   userAge   "&user_sex="   userSex;
        
        $.ajax({
          type:"post",
          url:addUrl,
          dataType:'json',
          contentType:'application/json;charset=utf-8',
          success:function(data){
            console.log("success");
          },
          error:function(data){
            console.log("data");
            //添加成功后隱蒧modal框
            setTimeout(function(){
              $('#exampleModal').modal('hide');
            },500);
              //隱藏modal框后重新加載當(dāng)前頁
            setTimeout(function(){
              searchData();
            },700);
          }
        });
      }

至此,還沒有解決如下問題:

1.表單驗(yàn)證;

2.添加多條數(shù)據(jù)后,php如何接收參數(shù);

3.新增成功后,在$.ajax的方法中,為什么,新增成功后的其它操作要在 error 這個(gè)對(duì)象中實(shí)現(xiàn)?而不是在 sucess 中實(shí)現(xiàn)?

更多關(guān)于云服務(wù)器,域名注冊(cè),虛擬主機(jī)的問題,請(qǐng)?jiān)L問西部數(shù)碼官網(wǎng):www.ps-sw.cn

贊(0)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享網(wǎng)絡(luò)內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-62778877-8306;郵箱:fanjiao@west.cn。本站原創(chuàng)內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明出處:西部數(shù)碼知識(shí)庫 » php之接口與前端數(shù)據(jù)交互實(shí)現(xiàn)示例代碼

登錄

找回密碼

注冊(cè)

皮山县| 沿河| 和林格尔县| 伽师县| 万全县| 鄂托克前旗| 小金县| 宁晋县| 东平县| 班戈县| 左权县| 额敏县| 红桥区| 乌兰察布市| 贵定县| 遂川县| 乾安县| 抚松县| 板桥市| 莱西市| 奉新县| 陇川县| 新丰县| 策勒县| 石景山区| 崇义县| 大丰市| 安徽省| 洪湖市| 罗江县| 彭泽县| 阳东县| 班戈县| 大姚县| 镇安县| 定西市| 永川市| 定安县| 旬阳县| 隆子县| 武定县|