[ JQuery ] [ Ajaxでテスト01 ] [ Ajaxでテスト03 ]
Ajaxでテスト02
- 2013-11-23 〜
※ jquery.jsを利用する設定がスクリプトのサンプルに記載されていませんが、省略してあり、実際は必要です。
サンプル
データを返すPHPのスクリプトではデータを用意するのが面倒なので、それらしいものを検索に利用したコードを使ってつくる。
データを検索するPHPコード
<?php
// コードで検索すると
// 品名、単位、単価、原価、備考を返すようなフリをする
// つまり、品名〜備考までに検索した「コード」をくっつけた
// ものをテキスト区切り(タブ)で返すものとする
$code = $_GET['code'];
$code =preg_replace('/\W/','', $code);
$r = "品名".$code."\t"
. "単位".$code."\t"
. "単価".$code."\t"
. "原価".$code."\t"
. "備考".$code."\t";
print $r;
?>
以下は、上記のようなPHPのスクリプトで検索した結果を明細の商品コードの様な感じで使う時の簡単なサンプル。上のスクリプトで、SQLやテキストをgrepで検索しても、数名が使うようなシステムでは十分使えると思います。最近のコンピュータのありがたさを実感します。
郵便番号データで検索してみるサンプルを作れば良いのかな。テキストデータですがあれだけのレコード件数がネット越しでも割とスムースに検索出来ると思います。
実行結果
codeを4桁入れてキーを離した時にイベント処理で、検索をするようなサンプルです。前回と変わった時に検索するような仕組みすると使い勝手が良くなると思います。
この部分のソース
<script>
$(function() {
html_meisai();
$("*[id^=id1-]").keyup(function() {
// alert(this.id);
id12 = this.id.split('-');
code = $("#"+this.id).val();
if (code.length==4 || code.length==0 ) {
if (code != '') {
kekka = search_code(code);
// alert("Row:"+id12[0]+" / Code:"+code+" / Result:"+kekka);
fld = kekka.split("\t");
$("#id2-"+id12[1]).val(fld[0]);
$("#id4-"+id12[1]).val(fld[1]);
$("#id5-"+id12[1]).val(fld[2]);
$("#id6-"+id12[1]).val(fld[3]);
$("#id7-"+id12[1]).val(fld[4]);
} else {
$("#id2-"+id12[1]).val("");
$("#id4-"+id12[1]).val("");
$("#id5-"+id12[1]).val("");
$("#id6-"+id12[1]).val("");
$("#id7-"+id12[1]).val("");
}
}
});
});
// ---------------------------------------------
function html_meisai() {
html = "<table>\n";
html += "<tr>";
html += "<th>行</th>";
html += "<th>コード</th>";
html += "<th>品名</th>";
html += "<th>数量</th>";
html += "<th>単位</th>";
html += "<th>単価</th>";
html += "<th>原価</th>";
html += "<th>備考</th>";
html += "</tr>";
for (i=0; i<10; i++) {
html += "<tr>";
html += "<td class='r0'>"+(i+1)+"</td>"; // 行
html += inp_text("id1-"+i,"4","r1"); // コード
html += inp_text("id2-"+i,"20","r2"); // 品名
html += inp_text("id3-"+i,"5","r3"); // 数量
html += inp_text("id4-"+i,"8","r4"); // 単位
html += inp_text("id5-"+i,"8","r5"); // 単価
html += inp_text("id6-"+i,"8","r6"); // 原価
html += inp_text("id7-"+i,"10","r7"); // 備考
html += "</tr>\n";
}
html += "</table>\n";
$("#meisai").html(html);
}
// ---------------------------------------------
function inp_text(id, size, classN) {
t = '<td class="'+classN+'"><input type="text" id="'+id
+'" size="'+size+'" class="'+classN+'"></td>';
return t;
}
// ---------------------------------------------
function search_code(code) {
var csv = $.ajax({
url: "sample_data/testcsv004.php?code="+code,
async: false
}).responseText;
return csv;
}
</script>
<div id="meisai"></div>
挑戦してください
Ajaxの簡単なサンプルを動かしてみました。
このページをご覧になっている方は、grepコマンドを使ってテキストファイルの検索をする事は特に問題ない方だと思います。PHPのexecコマンドなどを使えば使い慣れたgrepコマンドを利用して郵便番号データを検索できます。文字コード変換なども必要かと思いますが、Ajaxで全国版データを利用し、郵便番号からその住所を表示するサンプルを作成してみて下さい。
- 郵便番号データダウンロード
一応やってみよう→Ajaxでテスト03