Ajax基本まとめ
オブジェクト作成
function createXMLHttpRequest() { try { return new XMLHttpRequest(); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {} alert("XMLHttpRequest not supported"); return null; }
function createXMLHttpRequest(){ if (window.XMLHttpRequest){ return new XMLHttpRequest(); }else{ if (window.ActiveXObject){ return new ActiveXObject("Microsoft.XMLHTTP"); }else{ return null; } }
var xmlHttp; xmlHttp = new createXMLHttpRequest(); //([GET|POST], [url], [同期,非同期]) xmlHttp.open("GET", "./sample.text", false); //GETなら、null、POSTなら、送信したい文字列 xmlHttp.send(null);
var xmlHttp; xmlHttp = new createXMLHttpRequest(); //通信発生 if(xmlHttp) { var timerID = setTimeout("httpAbort()",5000); // タイムアウトを5秒に設定 xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState != 4) { //confirm } if (xmlHttp.status != 200){ // Handle error, Display error message on page } //if (xmlHttp.status == 200 && xmlHttp.readyState == 4) { clearTimeout(timerID); // タイムアウト用タイマー解除 var serverResponse = xhReq.responseText; //HTML(XML)を習得する際にはresponseXMLとすればよい。→DOMつかえる。 } //通信完了 xmlHttp.onload = function() { ... } } //([GET|POST], [url], [同期,非同期]) xmlHttp.open("GET", "./sample.text", true); //GETなら、null、POSTなら、送信したい文字列 xmlHttp.send(null);
readyStateの戻り値
値 状態
0:初期化がおこなわれていない
1:sendメソッドでデータが送られていない
2:sendメソッドは実行されているが応答がまだ無い
3:応答を受信している途中
4:全てのデータを受信済み
statusについて。
statusCode = new Array(); statusCode["200"] = function (){ alert(httpObj.responseText); } statusCode["401"] = function (){ alert("認証失敗"); } statusCode["403"] = function (){ alert("アクセスが許可されてません"); } statusCode["404"] = function (){ alert("ファイルがありません"); } statusCode["500"] = function (){ alert("内部エラー"); }