文章分類/

Infragistics|Ultimate UI Jquery|使用PHP的igGrid(用於JQuery的Ignite UI)的CRUD執行範例

493 瀏覽人次
2023-03-18 更新

infragistics log

本文將介紹如何通過連接PHP程式和igGrid去執行CRUD功能,以下是關於如何執行的說明。

  • 使用PHP從資料庫(Data Base)中獲取用於grid顯示用途的資料,並將其轉換為JSON資料。用ajax把對應資料綁定到grid上。
  • 點擊儲存按鈕,將對於行(Row)的新增、更新和刪除的相關異動一併傳送(Post)到PHP。PHP程式Post值並存入資料庫。

*本文目的在於說明如何使用ajax在grid和PHP之間傳遞資料,至於資料庫如何處理部分省略。

igGrid的準備

本篇文章準備了一個igGrid,其執行與下列的ASP.NET框架的範例相同。對row的編輯設置和grid的更動會被儲存在本地(local),並一次反映所有更新的執行。 https://jp.igniteui.com/grid/basic-editing

$(function () {     getData().done(function(result) {         var data = result;         var next_id = getAutoIncrement()["responseText"];         var grid = $("#grid").igGrid({             primaryKey: "id",             width: '100%',             columns: [                 { headerText: "ID", key: "id", dataType: "number", width: "15%" },                 { headerText: "First Name", key: "first_name", dataType: "string", width: "25%" },                 { headerText: "Last Name", key: "last_name", dataType: "string", width: "25%" },                 { headerText: "Birthday", key: "birthdate", dataType: "date", width: "35%" }             ],             autofitLastColumn: false,             autoGenerateColumns: false,             dataSource: data,             updateUrl : 'DataTransaction.php',             features: [                 {                     name: 'Updating',                     generatePrimaryKeyValue: function(evt, ui){                         ui.value = next_id;                     },                     rowAdded: function(evt, ui){                         next_id++;                     },                     columnSettings: [ {                         columnKey: "id",                         readOnly: true,                     }, {                         columnKey: "first_name",                         editorType: 'string',                         validation: true,                     }, {                         columnKey: "last_name",                         editorType: 'string',                         validation: true,                     }, {                         columnKey: "birthdate",                         editorType: 'date',                         validation: true,                     } ]                 }             ]         });         $("#saveChanges").igButton({ labelText: $("#saveChanges").val(), disabled: true });         $("#undo").igButton({ labelText: $("#undo").val(), disabled: true });         $("#redo").igButton({ labelText: $("#redo").val(), disabled: true });         loadingIndicator = new GridModalLoadingIndicator(grid);         grid.on("iggriddatabinding", function (e, args) {             loadingIndicator.show();         });         grid.on("iggriddatabound", function (e, args) {             loadingIndicator.hide();         });         grid.on("iggridupdatingrowdeleted", function (e, args) {             $("#undo").igButton("option", "disabled", false);             $("#saveChanges").igButton("option", "disabled", false);         });         grid.on("iggridupdatingrowadded", function (e, args) {             $("#undo").igButton("option", "disabled", false);             $("#saveChanges").igButton("option", "disabled", false);         });         grid.on("iggridupdatingeditrowended", function (e, args) {             if (args.update) {                 $("#undo").igButton("option", "disabled", false);                 $("#saveChanges").igButton("option", "disabled", false);             }         });         $("#undo").on('igbuttonclick',             function (e, args) {                 updates = $.extend({}, grid.data('igGrid').pendingTransactions());                 $.each(updates, function (index, transaction) {                     grid.igGrid("rollback", transaction.rowId, true);                 });                 $("#redo").igButton("option", "disabled", false);                 $("#undo").igButton("disable");                 $("#saveChanges").igButton("disable");                 return false;             }         );         $("#redo").on('igbuttonclick',             function (e) {                 $.each(updates, function (index, transaction) {                     switch (transaction.type) {                         case "row":                             grid.igGridUpdating('updateRow', transaction.rowId, transaction.row, null, false);                             break;                         case "newrow":                             grid.igGridUpdating('addRow', transaction.row, false);                             break;                         case "deleterow":                             grid.igGridUpdating('deleteRow', transaction.rowId, false);                             break;                     }                 });                 $(this).igButton("disable");                 $("#undo").igButton("option", "disabled", false);                 $("#saveChanges").igButton("option", "disabled", false);             }         );         $("#saveChanges").on('igbuttonclick',             function (e) {                 loadingIndicator.show();                 try {                     grid.igGrid("saveChanges",                     function (data) {                         console.log(data);                         loadingIndicator.hide();                         $("#undo").igButton("disable");                         $("#saveChanges").igButton("disable");                     },                     function (jqXHR, textStatus, errorThrown) {                         alert(JSON.stringify(jqXHR));                         alert(errorThrown);                         alert(JSON.stringify(textStatus));                     });                 } catch (e) {                     alert("error");                 }             }         );     }).fail(function(result) {         console.log(result);     }); }); 

使用ajax訪問PHP,獲取資料庫資訊,並綁定到grid。

創立了一個getData( )函數,範例如下。

function getData() {         return $.ajax({             type : "GET",             url : "DataTransaction.php",             dataType:'json',             success: function(data, status, xhr){                 //成功時的處理                 return data;             },             error: function(XMLHttpRequest, status, errorThrown){                 //失敗時的處理                 console.log("fail:" + status);             }         });  } 

在PHP端獲取資料庫資訊如下,轉成JSON回傳。此外,當使用PHP回傳JSON 時設置header。

header("Content-Type: application/json; charset=utf-8"); $sql = "SELECT * FROM authors"; if ($result = $mysqli->query($sql)) {     $data = [];     while ($row = $result->fetch_assoc()) {         array_push($data,$row);     }     $result->close(); } $mysqli->close(); echo json_encode($data); exit; 

將grid中的更動內容反映到資料庫中

由於在updateUrl屬性指定了一個PHP檔案,將igGrid中的更動內容反映到資料庫中。當您按下儲存按鈕時,更動資訊將發佈(POST)到被指定的URL。

updateUrl : 'DataTransaction.php', 

在接收了POST的PHP端,將接收到的JSON資料轉換為Array,並根據資料類型(newrow、deleterow、row)在Loop對資料庫的新增、刪除或更新。然後再次回傳json_encode(array(“Success”=>true)),藉以通知igGrid已處理完成。

header("Content-Type: application/json; charset=utf-8"); $post_data = $_POST["ig_transactions"]; $post_data_array = json_decode($post_data, true); $sql = ""; foreach ( $post_data_array as $row_data ) {     if ($row_data["type"] == "newrow") {         $id = $row_data["rowId"];         $first_name = $row_data["row"]["first_name"];         $last_name = $row_data["row"]["last_name"];         $birthdate = $row_data["row"]["birthdate"];         $sql .= "INSERT INTO `authors`(`id`, `first_name`, `last_name`, `birthdate`) VALUES ($id,'$first_name','$last_name','$birthdate');";     }     if ($row_data["type"] == "deleterow") {         $id = $row_data["rowId"];         $sql .= "DELETE FROM `authors` WHERE `id` = $id;";     }     if ($row_data["type"] == "row") {         $id = $row_data["rowId"];         $first_name = $row_data["row"]["first_name"];         $last_name = $row_data["row"]["last_name"];         $birthdate = $row_data["row"]["birthdate"];         $sql .= "UPDATE `authors` SET `id` = $id,`first_name` = '$first_name',`last_name` = '$last_name',`birthdate` = '$birthdate' WHERE `id` = $id; ";     } } $result = $mysqli->multi_query($sql); $mysqli->close(); echo json_encode(array("Success"=>true)); exit; 

對於PrimaryKey「值」的Auto Increment應對

新增row時需要特別注意一個地方,就是在資料庫的table中,id因為是作為主鍵使用,並在使用Auto Increment新增記錄(record)時會被賦予新的id,這情況被認為就如同有很多做法一般。另一方面,grid端終究只是用grid端持有的資訊来獲取下一個PrimaryKey的值,所以這種差異需要調整。

以本文範例而言,下一個ID值是在第一次繪製grid時先從mysql取得,每當觸發一次rowAdded事件,就會對應地造成ID值就會加1。另外在igGrid中新增row時被賦予的 ID 是可以通過修改generatePrimaryKeyValue 事件的回傳值「ui 」的ui.value來設定為任何值。

getData().done(function(result) {     var data = result;     var next_id = getAutoIncrement()["responseText"];     var grid = $("#grid").igGrid({         primaryKey: "id",         width: '100%',         columns: [             { headerText: "ID", key: "id", dataType: "number", width: "15%" },             { headerText: "First Name", key: "first_name", dataType: "string", width: "25%" },             { headerText: "Last Name", key: "last_name", dataType: "string", width: "25%" },             { headerText: "Birthday", key: "birthdate", dataType: "date", width: "35%" }         ],         autofitLastColumn: false,         autoGenerateColumns: false,         dataSource: data,         updateUrl : 'DataTransaction.php',         features: [             {                 name: 'Updating',                 generatePrimaryKeyValue: function(evt, ui){                     ui.value = next_id;                 },                 rowAdded: function(evt, ui){                     next_id++;                 },                 columnSettings: [ {                     columnKey: "id",                     readOnly: true,                 }, {                     columnKey: "first_name",                     editorType: 'string',                     validation: true,                 }, {                     columnKey: "last_name",                     editorType: 'string',                     validation: true,                 }, {                     columnKey: "birthdate",                     editorType: 'date',                     validation: true,                 } ]             }         ]     }); }).fail(function(result) {     console.log(result); }); 

執行範例

本文準備了如下表格:

範例執行後的grid所示如下。

下一步是,嘗試在grid上新增、更新和刪除。

將更改一併傳送到資料庫,按”Save”按鈕提交您的更改。

更改結果已呈現在grid和資料庫中。

以上就是本次文章。雖然這次內容沒有討論到安全性的部分,但應當注意的是,在向mysql發出query之前,ajax傳輸的CSRF對策和Injection對策會是必要的。

快速跳轉目錄

✦ 群昱 AccessSoft 你的全面軟體解決方案 ✦

身為全球眾多知名軟體在台灣合作夥伴,歡迎諮詢你需要的軟體服務!

Picture of 軟體專家
軟體專家

群昱作為全球知名軟體推薦合作夥伴,致力於提供更多軟體解決方案給你!

更多軟體新知

立即詢價

請留下完整資訊,以便我們提供精確的服務內容給你。

詢價資訊