日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

php 接口與前端數(shù)據(jù)交互實(shí)現(xiàn)示例代碼

 fanfl0517 2019-10-27

最近在做前后端數(shù)據(jù)交互的嘗試,也跳了很多坑,使用的是php+bootstrap-table+js,把一些收獲記錄在這里,方便查詢。

這個小項(xiàng)目,僅有3個文件,分別為:

1.crud.html
2.data.php
3.crud.sql

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

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

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

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

php:

<?php //測試php是否可以拿到數(shù)據(jù)庫中的數(shù)據(jù) /*echo '44444';*/ //做個路由 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(){ //測試 運(yùn)行crud.html時是否可以獲取到 下面這個字符串 /*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、返回一個包含參數(shù)列表的數(shù)組 * 3、遍歷$sqls這個數(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./bootstrap/3.3.7/css/bootstrap.min.css' rel='external nofollow' integrity='sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u' >    <!-- Latest compiled and minified CSS -->    <link rel='stylesheet' href='https://cdnjs./ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.css' rel='external nofollow' >    <!-- jQuery -->    <script type='text/javascript' src='http://code./jquery/1.11.2/jquery.min.js'></script>    <script type='text/javascript' src='http://code./jquery/plugins/jquery.cookie.js'></script>    <!-- bootstrap-table -->    <link rel='stylesheet' href='http://code./bootstrap-table/1.6.0/bootstrap-table.min.css' rel='external nofollow' >    <script type='text/javascript' src='http://code./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;'>    <div class='toolbar1' style='margin-bottom: -43px;'>      <button id='remove' class='btn btn-danger' disabled>刪除</button>      <button class='btn btn-primary' id='btn'>新建</button>    </div>    <div id='table'></div>    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->    <script src='https://cdn./bootstrap/3.3.7/js/bootstrap.min.js' integrity='sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa' ></script>    <!-- Latest compiled and minified JavaScript -->    <script src='//cdnjs./ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.js'></script>    <!-- Latest compiled and minified Locales -->    <script src='//cdnjs./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 中問號后面的參數(shù) action,這個對象就是查詢的參數(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) {            //測試是否可以拿到php中的數(shù)據(jù)            console.log(data);            //遍歷這個數(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ù)器出錯');          },        });      }      $('#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)效果:

數(shù)據(jù)交互實(shí)現(xiàn)2:刪除

在做刪除時遇到不少的坑,究其原因是因?yàn)閷QL語句不熟悉,對php不熟悉,不過,總結(jié)了以下幾點(diǎn),供參考:

1.delete 返回的參數(shù)只能用 $_GET 獲??;

2.delete 返回的參數(shù)要放在URL中,不能放在body中;body中的參數(shù)是用來查詢的;

3.SQL語句一定要熟練,一步錯,步步錯;

4.要在數(shù)據(jù)庫中執(zhí)行SQL語句檢查語句是否執(zhí)行正確,要使用 Rest Client 測試URL請求是否正確;

php:

<?php //測試php是否可以拿到數(shù)據(jù)庫中的數(shù)據(jù) /*echo '44444';*/ //做個路由 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(){ //測試 /*echo 'ok!';*/ //接收傳回的參數(shù) $rowId = $_GET['rowId']; $sql = 'delete from t_users where user_id='$rowId''; if(query_sql($sql)){ echo 'ok!'; }else{ echo '刪除失敗!'; } }?>

前端實(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) {              //返回選中的行的索引號              return row.user_id;            });          }                    $.map($table.bootstrapTable('getSelections'),function(row){            var del_url = './php/data.php';            //根據(jù)userId刪除數(shù)據(jù),因?yàn)檫@個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ù)較大,這個方法顯示是不可行的,但是還沒有找到合適的方法,煩請大俠們指點(diǎn)。

php:

<?php //測試php是否可以拿到數(shù)據(jù)庫中的數(shù)據(jù) /*echo '44444';*/ //做個路由 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 ('對應(yīng)的數(shù)據(jù)1','對應(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作為新增時的彈出框

<!--新增彈框-->    <div class='modal fade' id='exampleModal' tabindex='-1' role='dialog' aria-labelledby='exampleModalLabel'>      <div class='modal-dialog' role='document'>        <div class='modal-content'>          <div class='modal-header'>            <button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>×</span></button>            <h4 class='modal-title' id='exampleModalLabel'>用戶新增</h4>          </div>          <div class='modal-body'>            <form id='listForm' method='post'>              <div class='form-group'>                <label for='userName' class='control-label'>用戶名稱</label>                <input type='text' class='form-control' id='userName'>              </div>              <div class='form-group'>                <label for='userAge' class='control-label'>用戶年齡</label>                <input type='text' class='form-control' id='userAge'>              </div>              <div class='form-group'>                <label class='control-label' for='user-sex'>用戶性別</label>                <div class=''>                  <select id='user-sex' class='form-control' name='user-sex' style='width: 100%' >                    <option value='-1'>請選擇</option>                    <option value='0'>男</option>                    <option value='1'>女</option>                  </select>                </div>              </div>            </form>          </div>          <div 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>          </div>        </div>      </div>    </div>
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 這個對象中實(shí)現(xiàn)?而不是在 sucess 中實(shí)現(xiàn)?

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多