var xhr = new XMLHttpRequest();ざっと流れがわかったでしょうか。――では、実際に簡単なサンプルを挙げておきましょう。下のリスト欄は、サーバーにあるdata.txtというテキストを読み込んで表示する簡単な例です。ボタンを押すと、doActionが呼び出され、そこでAjax通信を行なっています。ここでは、以下のような形でopenをしていますね。
xhr.open('GET', 'アドレス', true);
xhr.responseType = 'text';
xhr.onload = function(e) {
if (this.status == 200) {
var result = this.response; // データ取得
}
};
xhr.send();
xhr.open('GET', '/data.txt', true);第1引数はGETかPOSTかの指定、第2引数にアドレス、そして第3引数に非同期通信かどうかを示す真偽値をそれぞれ指定します。後は、onloadでthis.statusをチェックし、200(正常終了)ならthis.responseを取り出して表示しておしまいです。実に簡単!
※リストが表示されない場合
AddBlockなどの広告ブロックツールがONになっているとリストなどが表示されない場合があります。これらのツールをOFFにしてみてください。
<!DOCTYPE html> <html lang="ja"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>タイトル</title> <style> h1 { font-size: 18pt; background: #AAAAEE; padding: 5px;} </style> <script type="text/javascript"> function doAction(e){ var xhr = new XMLHttpRequest(); xhr.open('GET', '/data.txt', true); xhr.responseType = 'text'; xhr.onload = function(e) { if (this.status == 200) { var result = this.response; document.querySelector("#msg").innerHTML = result; } }; xhr.send(); } </script> </head> <body> <header> <h1>XHR2 Sample</h1> </header> <article> <p id="msg"></p> <button onclick="doAction();">Click</button> </article> </body> </html>
<< 前へ | 次へ >> |