久久久久久久视色,久久电影免费精品,中文亚洲欧美乱码在线观看,在线免费播放AV片

<center id="vfaef"><input id="vfaef"><table id="vfaef"></table></input></center>

    <p id="vfaef"><kbd id="vfaef"></kbd></p>

    
    
    <pre id="vfaef"><u id="vfaef"></u></pre>

      <thead id="vfaef"><input id="vfaef"></input></thead>

    1. 站長資訊網(wǎng)
      最全最豐富的資訊網(wǎng)站

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

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

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

      這個小項目,僅有3個文件,分別為:

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

      相關學習推薦:PHP編程從入門到精通

      數(shù)據(jù)交互實現(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之接口與前端數(shù)據(jù)交互實現(xià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 init_data_list(){     //測試 運行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);   }         /**查詢服務器中的數(shù)據(jù)    * 1、連接數(shù)據(jù)庫,參數(shù)分別為 服務器地址 / 用戶名 / 密碼 / 數(shù)據(jù)庫名稱    * 2、返回一個包含參數(shù)列表的數(shù)組    * 3、遍歷$sqls這個數(shù)組,并把返回的值賦值給 $s    * 4、執(zhí)行一條mysql的查詢語句    * 5、關閉數(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;   } ?>

      前端實現(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 中問號后面的參數(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('服務器出錯');           },         });       }        $('#table').bootstrapTable({         pagination: true,         sidePagination: 'server', //設置為服務器端分頁         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>

      實現(xiàn)效果:

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

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

      在做刪除時遇到不少的坑,究其原因是因為對SQL語句不熟悉,對php不熟悉,不過,總結(jié)了以下幾點,供參考:

      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 "刪除失??!";     }   } ?>

      前端實現(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ù),因為這個id就是 傳給服務器的參數(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('刪除失?。?#39;);               }             });           });         })       }

      調(diào)試方法:

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

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

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

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

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

      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 ('對應的數(shù)據(jù)1','對應的數(shù)據(jù)2',...)     // VALUES 的值全為字符串,因為表屬性設置為字符串     $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;   } ?>

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

      html使用了bootstrap 的 modal作為新增時的彈出框

      <!--新增彈框-->     <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'>請選擇</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">關閉</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框后重新加載當前頁             setTimeout(function(){               searchData();             },700);           }         });       }

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

      1.表單驗證;

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

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

      贊(0)
      分享到: 更多 (0)
      網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號