[2020/04/11] JavaScript jQuery w2ui.grid を使ったグリッド処理・セルの編集設定(editable) (No.163)
[2020/04/10] JavaScript jQuery w2ui.grid を使ったグリッド処理・セルの書式設定(render) (No.162)
[2020/04/09] JavaScript jQuery w2ui.grid を使ったグリッド処理・外部データへ登録(save) (No.161)
[2020/04/03] JavaScript jQuery w2ui.grid を使ったグリッド処理・外部データの取り込み(url) (No.160)
-
今回は jQuery で用意されている when 関数を使って Ajax の逐次処理を行う方法について説明します。
先ずは Ajax でよくある勘違いに付いてですが Ajax の処理が終わった時点で行いたい処理を記述する以下の様な場合です。 以下のソースは Ajax の終了後 test1() が処理されることを期待しています。
しかし実際には、この場合 $.ajax(); の処理が行われた直後に test1() が実行されて、その後で testajax() が実行されるはずです。 $.ajax(); で実行される url はネットを通して行われるため通信に時間が掛かります。 通信が終了後、結果として done で宣言された関数の中の testajax() が実行されます。
$.ajax(); はあくまで関数宣言であり、最初は非同期通信の発火を行うだけです。 非同期通信の結果としての関数を done や fail で宣言します。■$.ajax の終了処理の勘違い
<script type="text/javascript"> // Ajax処理 $.ajax({ type: "POST", url: "hoge.php" }).done(function(data){ // 正常処理 testajax(); }); // 次の処理 test1(); </script>
上記の様に $.ajax(); の後に記述した処理を、本当に $.ajax(); の処理の終了後に行いたい場合に使うのが when です。
when の使い方ですが、以下の様な感じで when の中に Ajax 処理を行い when の done で行いたい処理を記述します。<whenの例> $.when( // ajax 等の処理 $.ajax({ type: "POST", url: "hoge.php" }).done(function(data){ // 正常処理 }).fail(function() { // 取得エラー }), // 次の処理 test1() ).done(function(){ // 後処理 }); <when の中の処理> ・複数の関数を呼出す場合は 「,」(カンマ)で区切ること。 <メソッド> ・done(function(data){}:when の中の処理が終了した場合に呼ばれる関数宣言。
上では Ajax 処理としていますが、別に Ajax にこだわらなくても、通常の関数処理でもOKです。 それでは Ajax ではない簡単な例を以下に示します。
■when の使い方HTMLファイル
<html> <head> <meta charset="utf-8"> <title>test ajax</title> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script type="text/javascript"> //when関数 function goWhen() { $.when( console.log("test-1"), console.log("test-2") ).done(function(){ // 後処理 console.log("test-end"); }); return false; } </script> </head> <body> <h2>test jquery when</h2> <button onclick="goWhen();">test when</button> </body> </html>
「test when」ボタンを押下するとコンソール画面に "test-1" "test-2" "test-end" の文字列が順次表示されるはずです。
それでは、以下の Ajax のページの処理に when を適用してみます。
⇒JavaScript jQueryでAjaxを使いPHPからデータを取得する方法
■when を適用:Ajaxを使いPHPからデータを取得するHTMLファイル
<html> <head> <meta charset="utf-8"> <title>test ajax</title> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script type="text/javascript"> //Ajax関数 function getData() { $.when( // マスタデータの取得 $.ajax({ type: "POST" , url: "./ajax1.php" , data: { id: $("#id").val() } }).done(function(res){ // ajaxがOK $("#msg").text(JSON.parse(res)); }).fail(function() { // 取得エラー alert('取得エラー'); }).always(function() { // 後処理(処理することが在れば) }) ).done(function(){ alert("ajax-end"); }); return false; } </script> </head> <body> <h2>test ajax json</h2> ID:<input type="text" id="id" size="10" maxlength="10" /><br /> <p id="msg">テストメッセージ</p> <button onclick="getData();">Ajax</button> </body> </html>
このソースで「Ajax」ボタンを押下した場合 $.ajax(); の処理が正常に行われれば メッセージ領域へのデータ表示の後にアラートで「ajax-end」の表示がされるはずです。
■外部PHPファイル ajax1.php
<?php // 処理モードの取得 $id = -1; if (isset($_POST["id"]) == true && $_POST["id"] != "") { $id = intval($_POST["id"]); } // マスタ風の仮のデータ $arrData = array( 0 => "@@@@@@" ,1 => "AAAAAA" ,2 => "BBBB" ,3 => "CCCCCCCC" ); $strRet = ""; if (0 <= $id && $id <= 3) { $strRet = $arrData[$id]; } // 結果を返す echo(json_encode($strRet));
PR -
今回は w2ui.grid のセルの編集設定の方法について説明します。
セルに対して入力出来る様に編集の種類を設定する場合は、グリッドのカラム宣言である columns プロパティの中の editable プロパティで行います。■editable の内部プロパティについて
プロパティ プロパティ名 説明 type 編集タイプ 宣言できるタイプは以下の通りです。 - text :文字型
- int :整数型
- float :実数型
- hex :16進数
- money :通貨型
- percent :パーセント
- currency :通貨型
- alphaNumeric:英数字
- date :日付型
- time :時刻型
- datetime :日付時刻型
- color :色設定
- check :チェックボックス
- list :ドロップダウンリスト
- combo :ドロップダウンリスト
- select :ドロップダウンリスト
min 入力最小値 数値項目で有効 max 入力最大値 数値項目で有効 precision 小数点以下桁数 precision:NN (NNは小数点以下の桁数)
数値項目で有効items 選択肢配列 items:items_array (items_arrayは静的変数の配列データ)
<例>
var items_array = [
{id:1, text:"text1"},
{id:2, text:"text2"},
{id:3, text:"text3"}
]
list、combo、select で有効style セルのスタイル <td> タグに追加するスタイル format 日付セルの書式 <例>
format:yyyy.mm.dd
この editable を使った簡単な例を以下に示します。<!DOCTYPE html> <html> <head> <title>w2ui Grid - editable</title> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" media="screen" href="./dist/w2ui.min.css" /> <script type="text/javascript" src="./libs/jquery/jquery-2.1.4.min.js"></script> <script type="text/javascript" src="./dist/w2ui.js"></script> </head> <body> <div id="grid" style="width: 600px; height: 240px;"></div> <br> <button class="w2ui-btn" onclick="showChanged()">変更データ表示</button> <script> // 性別データ var arrSex = [ {id:1, text:"男性"}, {id:2, text:"女性"} ]; $(function () { // id="grid" へのグリッド設定 $('#grid').w2grid({ name: 'grid', columns: [ { field: 'recid' , caption: 'ID' , size: '50px' , attr: "align=center", frozen: true }, { field: 'check' , caption: '対象' , size: '60px' , editable: { type:"checkbox" } }, { field: 'name' , caption: '名前' , size: '100px' , editable: { type:"text" } }, { field: 'age' , caption: '年齢' , size: '60px' , editable: { type:"int", min: 10, max: 99 } }, { field: 'sex' , caption: '性別' , size: '100px' , editable: { type:"select", items: arrSex } , render: function (record, index, col_index) { var html = ''; for (var idx in arrSex) { if (arrSex[idx].id == this.getCellValue(index, col_index)) { html = arrSex[idx].text; } } return html; } }, { field: 'birth' , caption: '生年月日', size: '100px' , render: 'date:yyyy/mm/dd', editable: { type:"date", format: "yyyy/mm/dd" } }, { field: "height", caption: "身長" , size: "50px" , render : "float:1", editable: { type:"float", min: 1, max: 999.9 } }, { field: "weight", caption: "体重" , size: "50px" , render : "float:1", editable: { type:"float", min: 1, max: 999.9 } } ], records: [ { recid:1, check:true , name:"田中太郎", age:"35", sex:"1", birth:"1985/03/01", height:"170.1", weight:"48.5" }, { recid:2, check:true , name:"田中花子", age:"30", sex:"2", birth:"1990/03/12", height:"160.0", weight:"45.0" }, { recid:3, check:true , name:"山田一郎", age:"20", sex:"1", birth:"2000/03/13", height:"165.1", weight:"58.5" }, { recid:4, check:false, name:"山田二郎", age:"18", sex:"1", birth:"2002/03/24", height:"172.5", weight:"68.2" }, { recid:5, check:true , name:"山田良子", age:"25", sex:"2", birth:"1995/03/25", height:"158.0", weight:"47.0" }, { recid:6, check:false, name:"山本桃子", age:"40", sex:"2", birth:"1980/03/26", height:"162.2", weight:"49.5" }, { recid:7, check:true , name:"山本次郎", age:"44", sex:"1", birth:"1976/03/27", height:"168.5", weight:"62.1" }, { recid:8, check:true , name:"阿部博" , age:"48", sex:"1", birth:"1972/03/28", height:"180.4", weight:"75.2" } ] }); }); function showChanged() { console.log(w2ui['grid'].getChanges()); w2alert('コンソールに変更データを表示しました'); } </script> </body> </html>
※「生年月日」の render の書式と editable 内の書式(format)を同じにしないと、カレンダーで変更後の表示がおかしくなります。
これを実行させると以下の様な表示になります。 (結構簡単にグリッドによるデータ表示が実現できると思います)
このグリッドの中で6行目の対象チェックボックスと性別、7行目の性別を変更し、変更データをコンソールに表示させてみると以下の様に配列データとして取得できます。 尚、性別データは文字列では無く ID の値が返されるのが分かります。この性別のセルで注目点は render の関数宣言です。関数の引数としては以下の様になっています。
render: function(record, [index], [column_index]) { } <引数> ・record:対象レコード ・index :対象レコードのインデックス値 ・column_index:対象レコード内のカラムインデックス値
性別のセルの処理では現在のセルの値が arrSex の配列の中で同じ id のものが見つかった時に対応する text の値を表示させています。
-
今回は w2ui.grid のセルの書式設定の方法について説明します。
セルに対して書式を設定する場合は、グリッドのカラム宣言である columns プロパティの中の render プロパティで行います。■render プロパティの定義済みの書式について
render名 書式 説明 int 整数値 float 浮動小数点数値 float:NN (NNは小数点以下の桁数) number 浮動小数点数値 number:NN (NNは小数点以下の桁数) money 金額 $9,999,999 の様にカンマ編集
($ はロケールにより変化する)currency 金額 $9,999,999 の様にカンマ編集
($ はロケールにより変化する)percent パーセント 数値をそのままパーセント値として表示(最後に%を付加) age 年齢 date 日付 date:date_format
(date_formatは日付書式、空の場合はd/m/yyyy)time 時刻 time:time_format
(time_formatは時刻書式、空の場合はd/m/yyyy)datetime 日付・時刻 datetime:date_format|time_format
(date_formatは日付書式、time_formatは時刻書式)toggle 使い方が不明 password パスワード 文字列の数だけ *(アスタリスク)の表示 function レンダリング関数 レンダリング関数:
render: function(record, [index], [column_index]) を宣言できる
それでは、上記の書式で使えそうなものを簡単な例で以下に示します。<!DOCTYPE html> <html> <head> <title>w2ui Grid-1</title> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" media="screen" href="./dist/w2ui.min.css" /> <script type="text/javascript" src="./libs/jquery/jquery-2.1.4.min.js"></script> <script type="text/javascript" src="./dist/w2ui.js"></script> </head> <body> <div id="grid" style="width: 800px; height: 250px;"></div> <script> $(function () { // id="grid" へのグリッド設定 $('#grid').w2grid({ name: 'grid', columns: [ { field: 'recid', caption: 'ID' , size: '40px' , render: 'float:2' }, { field: 'fname', caption: 'First Name', size: '80px' }, { field: 'lname', caption: 'Last Name' , size: '80px' , render: 'password'}, { field: 'fullname', caption: 'Full Name' , size: '100px', render: function (record) { return '<div>' + record.fname + ' ' + record.lname + '</div>'; } }, { field: 'email', caption: 'Email' , size: '20%' }, { field: 'sdate', caption: 'Birthday' , size: '100px', render: 'date:yyyy.mm.dd' }, { field: 'sdate', caption: 'age' , size: '80px' , render: 'age' }, { field: 'money', caption: 'Money' , size: '80px' , render: 'money' }, { field: 'money', caption: 'Money' , size: '80px' , render: 'percent' } ], records: [ { recid: 1, fname: "John" , lname: "Doe" , email: "jdoe@gmail.com", sdate: "1980/03/01", money: "1000" }, { recid: 2, fname: "Stuart" , lname: "Motzart", email: "smot@gmail.com", sdate: "2000/03/12", money: "200" }, { recid: 3, fname: "Jin" , lname: "Franson", email: "jgra@gmail.com", sdate: "2010/03/13", money: "30000" }, { recid: 4, fname: "Susan" , lname: "Ottie" , email: "sott@gmail.com", sdate: "1980/03/24", money: "40000" }, { recid: 5, fname: "Kelly" , lname: "Silver" , email: "ksil@gmail.com", sdate: "1970/03/25", money: "1000" }, { recid: 6, fname: "Francis", lname: "Gatos" , email: "fgat@gmail.com", sdate: "1982/03/26", money: "1500" }, { recid: 7, fname: "Mark" , lname: "Welldo" , email: "mwel@gmail.com", sdate: "2001/03/27", money: "10000" }, { recid: 8, fname: "Thomas" , lname: "Bahh" , email: "tbah@gmail.com", sdate: "2000/03/28", money: "10000" } ] }); }); </script> </body> </html>
これを実行させると以下の様な表示になります。
この例の中で興味深いのは、レンダリング関数を宣言できるところだと思います。
これを使えば各データの属性で色々な表示の変化を関数で処理できます。 例えば、データには区分データしか持っていないが、実際の場合にはそれに対応した文字列を表示したりできます。
レコードデータの中に男女区別のフラグを持ってそれで「男性」「女性」の違いを表示します。<!DOCTYPE html> <html> <head> <title>w2ui Grid-1</title> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" media="screen" href="./dist/w2ui.min.css" /> <script type="text/javascript" src="./libs/jquery/jquery-2.1.4.min.js"></script> <script type="text/javascript" src="./dist/w2ui.js"></script> </head> <body> <div id="grid" style="width: 500px; height: 250px;"></div> <script> // 性別文字列の宣言 var arrSex = {"1": "Male" , "2": "Female"}; $(function () { // id="grid" へのグリッド設定 $('#grid').w2grid({ name: 'grid', columns: [ { field: 'recid', caption: 'ID' , size: '60px' , render: 'float:2' }, { field: 'fname', caption: 'First Name', size: '100px' }, { field: 'lname', caption: 'Last Name' , size: '100px', render: 'password'}, { field: 'fullname', caption: 'Full Name' , size: '100px', render: function (record) { return '<div>' + record.fname + ' ' + record.lname + '</div>'; } }, { field: 'sex' , caption: 'Sex' , size: '20%' , render: function (record) { return '<div>' + arrSex[ record.sex ] + '</div>'; } } ], records: [ { recid: 1, fname: "John" , lname: "Doe" , sex: "1" }, { recid: 2, fname: "Stuart" , lname: "Motzart", sex: "1" }, { recid: 3, fname: "Jin" , lname: "Franson", sex: "1" }, { recid: 4, fname: "Susan" , lname: "Ottie" , sex: "2" }, { recid: 5, fname: "Kelly" , lname: "Silver" , sex: "2" }, { recid: 6, fname: "Francis", lname: "Gatos" , sex: "1" }, { recid: 7, fname: "Mark" , lname: "Welldo" , sex: "1" }, { recid: 8, fname: "Nuncy" , lname: "Bahh" , sex: "2" } ] }); }); </script> </body> </html>
これを実行させると以下の様な表示になります。
-
前回は w2ui.grid の外部データを指示するプロパティである url ついて説明をしました。
⇒JavaScript jQuery w2ui.grid を使ったグリッド処理・外部データの取り込み(url)
今回は url の save プロパティにPHPプログラムを指定することでデータ登録ができる例を紹介したいと思います。
尚、最初の読込ファイルは以下の様に以前のものと同様です。■JSON 形式のテストデータ(data-get.json)
{ records: [ { recid: 1, fname: "John" , lname: "Doe" , email: "jdoe@gmail.com", sdate: "2020/03/01" }, { recid: 2, fname: "Stuart" , lname: "Motzart", email: "smot@gmail.com", sdate: "2020/03/12" }, { recid: 3, fname: "Jin" , lname: "Franson", email: "jgra@gmail.com", sdate: "2020/03/13" }, { recid: 4, fname: "Susan" , lname: "Ottie" , email: "sott@gmail.com", sdate: "2020/03/24" }, { recid: 5, fname: "Kelly" , lname: "Silver" , email: "ksil@gmail.com", sdate: "2020/03/25" }, { recid: 6, fname: "Francis", lname: "Gatos" , email: "fgat@gmail.com", sdate: "2020/03/26" }, { recid: 7, fname: "Mark" , lname: "Welldo" , email: "mwel@gmail.com", sdate: "2020/03/27" }, { recid: 8, fname: "Thomas" , lname: "Bahh" , email: "tbah@gmail.com", sdate: "2020/03/28" } ] }
それでは records 部分を url にて JSON ファイルを指定したソースを示します。
■url プロパティによる JSON ファイルを指定について
<!DOCTYPE html> <html> <head> <title>w2ui Grid-3</title> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" media="screen" href="./dist/w2ui.min.css" /> <script type="text/javascript" src="./libs/jquery/jquery-2.1.4.min.js"></script> <script type="text/javascript" src="./dist/w2ui.js"></script> </head> <body> <div id="grid" style="width: 500px; height: 200px;"></div> <script> $(function () { // id="grid" へのグリッド設定 $('#grid').w2grid({ name: 'grid', method: 'GET', columns: [ { field: 'fname', caption: 'First Name', size: '30%' }, { field: 'lname', caption: 'Last Name' , size: '30%' }, { field: 'email', caption: 'Email' , size: '40%' }, { field: 'sdate', caption: 'Start Date', size: '100px' } ], url: { get: 'data-get.json', remove: 'save.php', save: 'save.php' } }); }); </script> </body> </html>
■save.php プログラム
<?php // PHP 5.5.0 未満のため「array_column」宣言 if (!function_exists('array_column')) { // 「array_column」宣言 function array_column($arr, $strKey) { $arrOut = array(); for ($i = 0; $i <= count($arr); $i++) { if (isset($arr[$i][$strKey])) { $arrOut[] = $arr[$i][$strKey]; } } return $arrOut; } } // リクエスト取得 $arrReq = json_decode($_GET['request'], true); $strJsonFile = 'data-get.json'; // 動作による処理 switch ($arrReq['action']) { case 'save': // 変更データ存在チェック if (!isset($arrReq['changes'][0])){ break; } // データJSONファイル $strJson = file_get_contents($strJsonFile); $arrData = json_decode($strJson, true); // recid列の配列(KEY:0からの連番) $arrRecid = array_column($arrData["records"], "recid"); // 変更データ('changes')に従って処理 for ($i = 0; $i <= count($arrReq['changes']) - 1; $i++) { $intRecid = -1; // 'changes'内の1個のデータ処理 foreach ($arrReq['changes'][$i] as $key => $value) { if ($key == "recid") { $intRecid = $value; // "recid"の退避 continue; } if ($intRecid >= 0) { // "recid"の存在するIndex検索 $intIdx = array_search($intRecid, $arrRecid); // データ配列への書込 $arrData["records"][$intIdx][$key] = $value; } } } // JSON文字列生成 $strJson = json_encode($arrData, JSON_UNESCAPED_UNICODE); // テキストファイル書込(data-get.json) file_put_contents($strJsonFile , $strJson); break; } ?>
最初の HTML ファイルを実行し、以下の図の Save ボタンをクリックすると data-get.json が変更され、 ページの再読込を行うと変更した値になるはずです。
上記は Save 処理のみのプログラムですが remove 処理も含めると以下の様になります。 行を複数選択して Delete ボタンをクリックすると以下の様に "recid" が配列で複数渡されます。
Array ( [request] => {"action":"delete","recid":[3,4]} )
これを加味してソースを修正します。
■save.php プログラム(削除処理も含む)
<?php // PHP 5.5.0 未満のため「array_column」宣言 if (!function_exists('array_column')) { // 「array_column」宣言 function array_column($arr, $strKey) { $arrOut = array(); for ($i = 0; $i <= count($arr); $i++) { if (isset($arr[$i][$strKey])) { $arrOut[] = $arr[$i][$strKey]; } } return $arrOut; } } // リクエスト取得 $arrReq = json_decode($_GET['request'], true); $strJsonFile = 'data-get.json'; // データJSONファイル $strJson = file_get_contents($strJsonFile); $arrData = json_decode($strJson, true); // 動作による処理 switch ($arrReq['action']) { case 'save': // 変更データ存在チェック if (!isset($arrReq['changes'][0])){ break; } // recid列の配列(KEY:0からの連番) $arrRecid = array_column($arrData["records"], "recid"); // 変更データ('changes')に従って処理 for ($i = 0; $i <= count($arrReq['changes']) - 1; $i++) { $intRecid = -1; // 'changes'内の1個のデータ処理 foreach ($arrReq['changes'][$i] as $key => $value) { if ($key == "recid") { $intRecid = $value; // "recid"の退避 continue; } if ($intRecid >= 0) { // "recid"の存在するIndex検索 $intIdx = array_search($intRecid, $arrRecid); // データ配列への書込 $arrData["records"][$intIdx][$key] = $value; } } } // JSON文字列生成 $strJson = json_encode($arrData, JSON_UNESCAPED_UNICODE); // テキストファイル書込(data-get.json) file_put_contents($strJsonFile , $strJson); break; case 'delete': // [request] => {"action":"delete","recid":[3,4]} // recid列の配列(KEY:0からの連番) $arrRecid = array_column($arrData["records"], "recid"); foreach ($arrReq['recid'] as $value) { // "recid"の存在するIndex検索 $intIdx = array_search($value, $arrRecid); // データ配列削除 unset($arrData["records"][$intIdx]); } $arrData["records"] = array_values($arrData["records"]); $arrData["total"] = count($arrData["records"]); // JSON文字列生成 $strJson = json_encode($arrData, JSON_UNESCAPED_UNICODE); // テキストファイル書込(data-get.json) file_put_contents($strJsonFile , $strJson); break; } ?>
今回はテキストファイルに対する登録、削除処理でしたが、実際にはデータベースに対しての処理になると思います。
-
今回は w2ui.grid の外部データを指示するプロパティである url ついて説明をします。
最初の紹介ページでのデータ宣言している部分を外部ファイルとして読込ませます。
⇒JavaScript jQuery w2ui.grid を使ったグリッド処理方法の紹介
ファイルは JSON 形式で記述します。上記のページの records プロパティの部分を JSON ファイルとして作成します。
ファイルの中身は以下の様になります。(records を { } で囲みます。尚、ファイルの文字コードは UTF-8 です。){ records: [ { recid: 1, fname: "John" , lname: "Doe" , email: "jdoe@gmail.com", sdate: "2020/03/01" }, { recid: 2, fname: "Stuart" , lname: "Motzart", email: "smot@gmail.com", sdate: "2020/03/12" }, { recid: 3, fname: "Jin" , lname: "Franson", email: "jgra@gmail.com", sdate: "2020/03/13" }, { recid: 4, fname: "Susan" , lname: "Ottie" , email: "sott@gmail.com", sdate: "2020/03/24" }, { recid: 5, fname: "Kelly" , lname: "Silver" , email: "ksil@gmail.com", sdate: "2020/03/25" }, { recid: 6, fname: "Francis", lname: "Gatos" , email: "fgat@gmail.com", sdate: "2020/03/26" }, { recid: 7, fname: "Mark" , lname: "Welldo" , email: "mwel@gmail.com", sdate: "2020/03/27" }, { recid: 8, fname: "Thomas" , lname: "Bahh" , email: "tbah@gmail.com", sdate: "2020/03/28" } ] }
それでは records 部分を url にて JSON ファイルを指定したソースを示します。
■url プロパティによる JSON ファイルを指定について
<!DOCTYPE html> <html> <head> <title>w2ui Grid-1</title> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" media="screen" href="./dist/w2ui.min.css" /> <script type="text/javascript" src="./libs/jquery/jquery-2.1.4.min.js"></script> <script type="text/javascript" src="./dist/w2ui.js"></script> </head> <body> <div id="grid" style="width: 500px; height: 200px;"></div> <script> $(function () { // id="grid" へのグリッド設定 $('#grid').w2grid({ name: 'grid', columns: [ { field: 'fname', caption: 'First Name', size: '30%' }, { field: 'lname', caption: 'Last Name' , size: '30%' }, { field: 'email', caption: 'Email' , size: '40%' }, { field: 'sdate', caption: 'Start Date', size: '100px' } ], url: 'data.json' }); }); </script> </body> </html>
これを実行させると以下の様な表示になります。 (特に最初の紹介ページの表示と変わりはありません)
この url はグリッドが、リフレッシュ、検索、レコードのソートの各処理が行われた時にしていされた url で指定されたファイルからデータが取得されて表示されます。 データを保存する場合があれば、同じく url で指定されたファイルに登録されます。
更に、レコードの取得、削除、登録において別のファイル名などを指定する場合は url の内部プロパティである get , remove , save を指定します。
■url プロパティによるレコードの取得、削除、登録を指定
<!DOCTYPE html> <html> <head> <title>w2ui Grid-1</title> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" media="screen" href="./dist/w2ui.min.css" /> <script type="text/javascript" src="./libs/jquery/jquery-2.1.4.min.js"></script> <script type="text/javascript" src="./dist/w2ui.js"></script> </head> <body> <div id="grid" style="width: 500px; height: 200px;"></div> <script> $(function () { // id="grid" へのグリッド設定 $('#grid').w2grid({ name: 'grid', columns: [ { field: 'fname', caption: 'First Name', size: '30%' }, { field: 'lname', caption: 'Last Name' , size: '30%' }, { field: 'email', caption: 'Email' , size: '40%' }, { field: 'sdate', caption: 'Start Date', size: '100px' } ], url: { get: 'data-get.json', remove: 'data-remove.json', save: 'datas-save.json' } }); }); </script> </body> </html>
この方法で上手くいくかと思ったのですが、remove , save のところで json ファイル指定はできない様です。 以下のソースの様に PHP ファイルに制御を渡して、 $_GET['request'] の中を調べてデータ処理をすることになります。
<!DOCTYPE html> <html> <head> <title>w2ui Grid-2 url2</title> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" media="screen" href="./dist/w2ui.min.css" /> <script type="text/javascript" src="./libs/jquery/jquery-2.1.4.min.js"></script> <script type="text/javascript" src="./dist/w2ui.js"></script> </head> <body> <div id="grid" style="width: 500px; height: 200px;"></div> <script> $(function () { // id="grid" へのグリッド設定 $('#grid').w2grid({ name: 'grid', method: 'GET', columns: [ { field: 'recid', caption: 'ID', size: '50px' }, { field: 'fname', caption: 'First Name', size: '30%' , editable: { type: 'text' } }, { field: 'lname', caption: 'Last Name' , size: '30%' }, { field: 'email', caption: 'Email' , size: '40%' }, { field: 'sdate', caption: 'Start Date', size: '100px' } ], url: { get: 'data-get.json', remove: 'remove.php', save: 'save.php' }, show : { toolbar : true, toolbarDelete : true, toolbarSave : true, searchAll : false } }); }); </script> </body> </html>
このソースを表示し、グリッドの Save ボタンをクリックすると変更個所の情報が PHP プログラムに送られます。■save.php プログラム
<?php $results = print_r($_GET, true); file_put_contents("save.json", $results); ?>
■save.json ファイルの内容
Array ( [request] => {"changes":[{"recid":3,"fname":"Jin111"},{"recid":4,"fname":"Susan222"}],"action":"save"} )
変更の在った recid と 変更したカラム名とその値が送られてくるので、それを使って実際のデータを更新処理することになります。
グリッドの行を選択し Delete ボタンをクリックすると削除個所の情報が PHP プログラムに送られます。■remove.php プログラム
<?php $results = print_r($_GET, true); file_put_contents("remove.json", $results); ?>
■remove.json ファイルの内容
Array ( [request] => {"action":"delete","recid":[1]} )
削除の在った recid が送られてくるので、それを使って実際のデータを削除処理することになります。