這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)如何實(shí)現(xiàn)php之接口與前端數(shù)據(jù)交互,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
成都創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比西工網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式西工網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋西工地區(qū)。費(fèi)用合理售后完善,十載實(shí)體公司更值得信賴。
最近在做前后端數(shù)據(jù)交互的嘗試,也跳了很多坑,使用的是php+bootstrap-table+js,把一些收獲記錄在這里,方便查詢。
這個(gè)小項(xiàng)目,僅有3個(gè)文件,分別為:
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ù)庫建表
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 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/K68vbdEjh5u" 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)效果:
數(shù)據(jù)交互實(shí)現(xiàn)2:刪除
在做刪除時(shí)遇到不少的坑,究其原因是因?yàn)閷?duì)SQL語句不熟悉,對(duì)php不熟悉,不過,總結(jié)了以下幾點(diǎn),供參考:
1.delete 返回的參數(shù)只能用 $_GET 獲取;
2.delete 返回的參數(shù)要放在URL中,不能放在body中;body中的參數(shù)是用來查詢的;
3.SQL語句一定要熟練,一步錯(cuò),步步錯(cuò);
4.要在數(shù)據(jù)庫中執(zhí)行SQL語句檢查語句是否執(zhí)行正確,要使用 Rest Client 測(cè)試URL請(qǐng)求是否正確;
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 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">×</span></button> <h5 class="modal-title" id="exampleModalLabel">用戶新增</h5> </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)?
上述就是小編為大家分享的如何實(shí)現(xiàn)php之接口與前端數(shù)據(jù)交互了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
當(dāng)前題目:如何實(shí)現(xiàn)php之接口與前端數(shù)據(jù)交互
標(biāo)題來源:http://muchs.cn/article8/ihchop.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計(jì)、電子商務(wù)、網(wǎng)頁設(shè)計(jì)公司、ChatGPT、用戶體驗(yàn)、靜態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)