onreadystatechange

書式

オブジェクト.onreadystatechange = "イベント発生時の処理"

説明

状態が変化した時に発生するイベントです。

サンプルコード [実行]

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Sample</title>
<script type="text/javascript"><!--
function loadTextFile() {
httpObj = createXMLHttpRequest(displayData);
if (httpObj) {
httpObj.open("get","data.txt",true);
httpObj.send(null);
}
}
function displayData() {
if ((httpObj.readyState == 4) && (httpObj.status == 200)) {
document.getElementById("result").value = httpObj.responseText;
}
}
// HTTP通信用、共通関数
function createXMLHttpRequest(cbFunc) {
var XMLhttpObject = null;
try{ XMLhttpObject = new XMLHttpRequest();
}catch(e){
try{ XMLhttpObject = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{ XMLhttpObject = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){ return null; }
}
}
if (XMLhttpObject) XMLhttpObject.onreadystatechange = cbFunc;
return XMLhttpObject;
}
// --></script>
</head>
<body>
<h1>onReadyState Change</h1>
<form name="ajaxForm">
<input type="button" value="読み込み" onClick="loadTextFile()"><br>
<textarea name="result" cols="40" rows="5" id="result"></textarea>
</form>
</body>
</html>