LoginSignup
39
47

More than 1 year has passed since last update.

jQueryで外部CSVファイルをロードする

Last updated at Posted at 2018-07-05

外部CSVファイルからデータを取得して、javascriptで操作したい場合がある。そんなときには、jQueryとjquery.csv.jsを使うのが最も簡単である。

ところが、この方法を紹介しているサイトがいくつかあるのに、紹介されているコードを実行しても動作しなかった。これは、jquery.csv.jsのバージョンアップや開発環境の変化のためである。そこで、現在の時点(2023-04-13)で動作するコードを紹介する。

jquery.csv.jp の環境変化

まず、jquery.csv.jpに起きた変化を上げる。他サイトのコードが動作しなかった原因である。

$.csv()(data) は使えない

jquery.csv.jsの現在のバージョンは1.0.21である。バージョンアップのため、他サイトで紹介されている

var csv = $.csv()(data)

のようなコードは使えなくなっている。以下のように置き換える。

var csv = $.csv.toArrays(data)

開発場所

以前はGoogleのサイトで開発されていたようだが、現在はGitHubに移動している。

CDNサイトの場所

最新版のURLは以下である。

$.get()でdataTypeを指定する

こちらは、jquery.csv.jsではなくjQueryの問題だが、$.get()でdataTypeを指定する必要がある。他サイトでdataTypeをつけていないコードがあったが、これを省略するとparseerrorが出る場合がある(ブラウザやjQueryのバージョンによるので、必ずエラーになるわけではない)。

$.get(csvfile, readCsv);  -->  $.get(csvfile, readCsv, 'text');

コードの例

以上に対応したhtmlのコード例をリスト1に示す。なお、test.csvはリスト2のようになっている。図1はブラウザ画面のスクリーンショットである。

リスト1
<!DOCTYPE html>
<html lang="ja">
<head>
	<meta charset="utf-8">
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"
	  integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
	  crossorigin="anonymous"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/1.0.21/jquery.csv.min.js"></script>
	<script>
		function readCsv(data) {
			var target = '#csv-body';
			var csv = $.csv.toArrays(data);
			var insert = '';
			$(csv).each(function() {
				if (this.length > 0) {
					insert += '<tr>';
					$(this).each(function() {
						insert += '<td>' + this + '</td>';
					});
					insert += '</tr>';
				}
			});
			$(target).append(insert);
		}
		var csvfile = 'test.csv';
		$(function(){
			$.get(csvfile, readCsv, 'text');
		});
	</script>
	<link rel='stylesheet' href='list.css'>
</head>
<body>
	<table>
		<caption>紫陽花の名所</caption>
		<thead>
			<tr><th>名前</th><th>場所</th><th>種類</th><th>株数</th></tr>
		</thead>
		<tbody id='csv-body' />
	</table>
</body>
</html>
リスト2
"恋し野の里あじさい園","和歌山県橋本市",30,6000
"矢田寺","奈良県大和郡山市",60,8000
"吉野山","奈良県吉野郡吉野町",,4000
(以下略)

図1 スクリーンショット

変更履歴

  • 2023-04-20: CDN におけるバージョンを修正(1.0.11 -> 1.0.21)
  • 2021-12-08: jquery.csv.js のバージョンを修正(1.0.11 -> 1.0.21)
    jquery.js のバージョン(3.5.1 -> 3.6.01.0.21)およびintegrityを修正
  • 2020-10-14: jquery.csv.js のバージョンを修正(1.0.08 -> 1.0.11)
  • 2019-12-27: jquery.csv.js のバージョンを修正(1.0.5 -> 1.0.8)
  • 2019-10-19: jquery.jsのCDNについて、jQueryサイトの指定に従って、<script>ノードの記述を変更
  • 2019-08-26: jquery.csv.js のバージョンを修正(0.8.9 -> 1.0.5)
39
47
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
47