ようやくAjax
hello_ajax.html
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <title>hello Ajax!</title> <script type="text/javascript" src="hello_ajax.js"></script> </head> <body> <div id="hello">送信ボタンを押してください</div> <p><input type="button" id="btn" value="送信" /></p> </body> </html>
hello_ajax.js
//グローバル変数の定義 var httpObj; var timerId; var timeout_sec = 10; //タイムアウトの秒数 //テキストの内容を表示 function helloAjax(){ // テキストファイルのURL var target_url = 'hello.txt'; // 処理を実行するための関数リファレンスを定義 var funcRef = function(text_data){ document.getElementById('hello').childNodes[0].nodeValue = text_data; } // http通信を開始し、完了したら上記関数を実行させる httpRequest(target_url,funcRef); } // 引数に与えられたURLにHTTPリクエストを行い、指定された関数を実行 function httpRequest(target_url, functionReference){ try{ if(window.XMLHttpRequest){ httpObj = new XMLHttpRequest(); } else if(window.ActiveXObject){ httpObj = new ActiveXObject("Microsoft.XMLHTTP"); } else { httpObj = false; } } catch(e){ httpObj = false; } if(! httpObj){ httpObjGenerateFail(); } // タイマーセット timerId = setInterval('timeoutCheck()', 1000); httpObj.open("GET", target_url, true); httpObj.onreadystatechange= function(){ if (httpObj.readyState == 4){ clearInterval(timerId); if (httpObj.status == 200){ functionReference(httpObj.responseText); } else { alert(httpObj.status + ' : ' + httpObj.statusText); return false; } } } httpObj.send(''); } // XMLHttpRequestオブジェクトの生成に失敗した場合 function httpObjGenerateFail(){ alert('ご利用のブラウザは当サイトを利用できません!'); return false; } // HTTPタイムアウトの処理 function timeoutCheck(){ timeout_sec --; if(timeout_sec <= 0){ clearInterval(timerId); httpObj.abort(); alert('タイムアウト'); return false; } } // イベントリスナーをセットする function setListeners(e){ var sendBtn = document.getElementById('btn'); addListener(sendBtn, 'click', helloAjax, false); } function addListener(elem, eventType, func, cap){ if(elem.addEventListener){ elem.addEventListener(eventType,func,cap); } else if(elem.attachEvent){ elem.attachEvent('on'+eventType,func); } else { alert('ご利用のブラウザは対応していません!'); return false; } } addListener(window,'load',setListeners,false);
ポイント
var funcRef = function(text_data){ document.getElementById('hello').childNodes[0].nodeValue = text_data; }
無名関数。簡単な処理なら関数内で定義出来る。
長くなるなら、名前を付けて普通の関数にするべき。
httpRequest(target_url,funcRef);
httpRequestでHTTP通信をしている。httpRequestないでは、ブラウザーに応じて通信用のオブジェクトを生成している。