CSVファイルもjQueryの$.ajaxメソッドを使ってサーバから読み込むことができる。
その方法は次のとおりである。
$(function(){
$('#btn').click(function(){
// CSV形式のファイルを読み込み
$.ajax({
url:'csvname2.csv',
type:'get',
dataType:'text', // CSV形式のデータを受信
cache:false,
success: function(csv){
var rows = $.csv()(csv); // CSVを配列に変換
// <table>,<th>,<td>の生成と表示
var table = $('<table>').appendTo(document.body);
$.each(rows,function(rIdx,row){
var tr = $('<tr>').appendTo(table);
$.each(row,function(cIdx,column){
if(rIdx == 0){
$('<th>',{text:column}).appendTo(tr);
}else{
$('<td>',{text:column,css:{textAlign:isNaN(column) ? 'left' : 'center'}})
.appendTo(tr);
}
});
});
}
});
});
});
url:にてCSVファイルを指定し、dataType:でtextを指定する。
読み込んだ後はCSVを配列に変換する。変換はjQueryプラグインがあったので利用させて頂いた。
プラグインのソースコード(これを使いやすいようにjquery.csv.jsにしておく)
/* Usage:
* jQuery.csv()(csvtext) returns an array of arrays representing the CSV text.
* jQuery.csv("\t")(tsvtext) uses Tab as a delimiter (comma is the default)
* jQuery.csv("\t", "'")(tsvtext) uses a single quote as the quote character instead of double quotes
* jQuery.csv("\t", "'\"")(tsvtext) uses single & double quotes as the quote character
* jQuery.csv(",", "", "\n")(tsvtext) カンマ区切りで改行コード「\n」
*/
jQuery.extend({
csv: function(delim, quote, lined) {
delim = typeof delim == "string" ? new RegExp( "[" + (delim || "," ) + "]" ) : typeof delim == "undefined" ? "," : delim;
quote = typeof quote == "string" ? new RegExp("^[" + (quote || '"' ) + "]" ) : typeof quote == "undefined" ? '"' : quote;
lined = typeof lined == "string" ? new RegExp( "[" + (lined || "\r\n") + "]+") : typeof lined == "undefined" ? "\r\n" : lined;
function splitline (v) {
// Split the line using the delimitor
var arr = v.split(delim), out = [], q;
for (var i=0, l=arr.length; i<l; i++) {
if (q = arr[i].match(quote)) {
for (j=i; j<l; j++) {
if (arr[j].charAt(arr[j].length-1) == q[0]) {
break;
}
}
var s = arr.slice(i,j+1).join(delim);
out.push(s.substr(1,s.length-2));
i = j;
}
else {
out.push(arr[i]);
}
}
return out;
}
return function(text) {
var lines = text.split(lined);
for (var i=0, l=lines.length; i<l; i++) {
lines[i] = splitline(lines[i]);
}
// 最後の行を削除
var last = lines.length - 1;
if (lines[last].length == 1 && lines[last][0] == "") {
lines.splice(last, 1);
}
return lines;
};
}
});
変換の使い方は次のとおりである。
var rows = $.csv()(csvデータ);
上記の例はCSVデータがrowsに二次元配列で変換される。