リクエストをサーバに送った時、レスポンスに基づいた何等かのアクションを実行したいとします。
readyState が変ると、常に onreadystatechange イベントがトリガーされます。
readyState プロパティは、XMLHttpRequest のステータスを持っています。
XMLHttpRequest オブジェクトの重要な 3 つのプロパティは次の通り:
プロパティ | 説明 |
---|---|
onreadystatechange | readyState プロパティが変わるごとに自動的に呼ばれる関数(あるいは関数名)を格納する |
readyState | XMLHttpRequest のステータスを保持する。0 から 4 までに変化する: 0: リクエストは初期化されていない 1: サーバ接続は確立した 2: リクエストを受信した 3: リクエストの処理中 4: リクエストは終了してレスポンスの準備が完了 |
status | 200: "OK" 404: Page not found |
サーバ・レスポンスの処理が完了した場合、onreadystatechange イベントに何をするかを指定します。
readyState が 4 で、ステータスが 200 である場合、レスポンスの処理は完了です:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt",
true);
xhttp.send();
}
Try it Yourself »
注: readyState の変化に対して各 1 回、合計 4 回の onreadystatechange イベントが発生します。
コールバック関数は、他の関数にパラメーターとして渡される関数です。
Web サイトに複数の AJAX タスクがある場合、XMLHttpRequest オブジェクトを作成するための 1 つの標準関数を作成し、 各 AJAX タスクはこれをコールします。
関数コールには、URL および onreadystatechange(恐らく各コール毎に異なる)で何をするかが含まれているべきです:
function loadDoc(url, cfunc) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange =
function() {
if (this.readyState
== 4 && this.status == 200) {
cfunc(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
Try it Yourself »