JavascriptでXMLhttpRequestを利用してファイル読み込みする処理のサンプルプログラムを紹介します。
非同期でファイルを読み込む方法
非同期データ取得ボタンをクリックすると、同じフォルダ内のtest.txtを読み込んで画面に表示します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS"> <title>XMLHttpRequest 非同期処理</title> <script type="text/javascript"> /* 指定したテキストファイルを読込み、ファイルの内容をそのまま返す * url:読み込むファイルパス */ function ReadTextFile(url) { var xml = new XMLHttpRequest(); xml.onreadystatechange=function(){ if (xml.readyState == 4 && xml.status == 200){ document.getElementById("display").innerHTML= xml.responseText; }else if( xml.status == 404){ alert("ファイルがみつかりません。"); } } xml.overrideMimeType('text/plain; charset=EUC-JP'); //文字コード指定 //xml.open(,ファイルパス,(true:非同期,false:同期); xml.open("GET", url+"?cache=" + (new Date()).getTime(), true); xml.send(null); } </script> </head> <body> <input id="Button_Get" type="button" value="非同期データ取得" onclick="ReadTextFile('./test.txt');" /> <div id="display"></div> </body> </html> |
同期でファイルを読み込む方法
同期データ取得ボタンをクリックすると、同じフォルダ内のtest.txtを読み込んで画面に表示します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS"> <title>XMLHttpRequest 同期処理</title> <script type="text/javascript"> /* 指定したテキストファイルを読込み、ファイルの内容をそのまま返す * url:読み込むファイルパス */ function ReadTextFile(url) { var xml = new XMLHttpRequest(); //xml.open(,ファイルパス,(true:非同期,false:同期); xml.open("GET", url+"?cache=" + (new Date()).getTime(), false); xml.overrideMimeType('text/plain; charset=EUC-JP'); //文字コード指定 xml.send(); document.getElementById("display").innerHTML= xml.responseText; } </script> </head> <body> <input id="Button_Get" type="button" value="同期データ取得" onclick="ReadTextFile('./test.txt');" /> <div id="display"></div> </body> </html> |
よく利用するプロパティ
onreadystatechange
readyStateが変化した時に実行される処理を設定できる
readyState
サーバーからのレスポンス状況を取得する。
ファイルを読み込む時は4の状態になっているか確認する。
番号 | 状態 |
0 | 初期化がおこなわれていない |
1 | sendメソッドでデータが送られていない |
2 | sendメソッドは実行されているが応答がまだ無い |
3 | データ受信中 |
4 | データ受信済み |
status
ステータス番号が取得できる。
ファイルを読み込む時は200の状態になっているか確認する。
ステータス番号 | 状態 |
200 | OK |
401 | Unauthorized |
403 | Forbidden |
404 | Not Found |
500 | Internal Server Error |
プロパティの説明はこちらを参照させていただきました。
https://www.ajaxtower.jp/ini/http/index2.html