AJAX-XMLHttpRequestオブジェクト
AJAXの要はXMLHttpRequestオブジェクトです。
- XMLHttpRequestオブジェクトを作成します
- コールバック関数を定義する
- XMLHttpRequestオブジェクトを開きます
- サーバーにリクエストを送信する
XMLHttpRequestオブジェクト
最新のブラウザはすべてこのXMLHttpRequest
オブジェクトをサポートしています。
このXMLHttpRequest
オブジェクトは、舞台裏でWebサーバーとデータを交換するために使用できます。これは、ページ全体をリロードすることなく、Webページの一部を更新できることを意味します。
XMLHttpRequestオブジェクトを作成する
最新のブラウザ(Chrome、Firefox、IE、Edge、Safari、Opera)にはすべて、XMLHttpRequest
オブジェクトが組み込まれています。
XMLHttpRequest
オブジェクトを作成するための構文:
variable = new XMLHttpRequest();
コールバック関数を定義する
コールバック関数は、パラメータとして別の関数に渡される関数です。
この場合、コールバック関数には、応答の準備ができたときに実行するコードが含まれている必要があります。
xhttp.onload = function() {
// What to do when the response is ready
}
リクエストを送信する
XMLHttpRequest
サーバーにリクエストを送信するには、オブジェクトのopen()メソッドとsend()メソッドを使用でき
ます。
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
例
// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();
// Define a callback function
xhttp.onload = function() {
// Here you can use the Data
}
// Send a request
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
ドメイン間でのアクセス
セキュリティ上の理由から、最近のブラウザはドメイン間でのアクセスを許可していません。
これは、WebページとそれがロードしようとするXMLファイルの両方が同じサーバー上にある必要があることを意味します。
W3Schoolsの例はすべて、W3SchoolsドメインにあるXMLファイルを開きます。
上記の例を独自のWebページのいずれかで使用する場合は、ロードするXMLファイルを独自のサーバーに配置する必要があります。
XMLHttpRequestオブジェクトメソッド
Method | Description |
---|---|
new XMLHttpRequest() | Creates a new XMLHttpRequest object |
abort() | Cancels the current request |
getAllResponseHeaders() | Returns header information |
getResponseHeader() | Returns specific header information |
open(method, url, async, user, psw) | Specifies the request method: the request type GET or POST url: the file location async: true (asynchronous) or false (synchronous) user: optional user name psw: optional password |
send() | Sends the request to the server Used for GET requests |
send(string) | Sends the request to the server. Used for POST requests |
setRequestHeader() | Adds a label/value pair to the header to be sent |
XMLHttpRequestオブジェクトのプロパティ
Property | Description |
---|---|
onload | Defines a function to be called when the request is recieved (loaded) |
onreadystatechange | Defines a function to be called when the readyState property changes |
readyState | Holds the status of the XMLHttpRequest. 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready |
responseText | Returns the response data as a string |
responseXML | Returns the response data as XML data |
status | Returns the status-number of a request 200: "OK" 403: "Forbidden" 404: "Not Found" For a complete list go to the Http Messages Reference |
statusText | Returns the status-text (e.g. "OK" or "Not Found") |
onloadプロパティ
このXMLHttpRequest
オブジェクトを使用すると、リクエストが応答を受け取ったときに実行されるコールバック関数を定義できます。
関数は、オブジェクトのonload
プロパティで定義されています。XMLHttpRequest
例
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
複数のコールバック関数
Webサイトに複数のAJAXタスクがある場合は、オブジェクトを実行するための1つの関数とXMLHttpRequest
、AJAXタスクごとに1つのコールバック関数を作成する必要があります。
関数呼び出しには、URLと、応答の準備ができたときに呼び出す関数が含まれている必要があります。
例
loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);
function loadDoc(url, cFunction) {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {cFunction(this);}
xhttp.open("GET", url);
xhttp.send();
}
function myFunction1(xhttp) {
// action goes here
}
function myFunction2(xhttp) {
// action goes here
}
onreadystatechangeプロパティ
このreadyState
プロパティは、XMLHttpRequestのステータスを保持します。
このonreadystatechange
プロパティは、readyStateが変更されたときに実行されるコールバック関数を定義します。
status
プロパティとプロパティはstatusText
、XMLHttpRequestオブジェクトのステータスを保持します。
Property | Description |
---|---|
onreadystatechange | Defines a function to be called when the readyState property changes |
readyState | Holds the status of the XMLHttpRequest. 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready |
status | 200: "OK" 403: "Forbidden" 404: "Page not found" For a complete list go to the Http Messages Reference |
statusText | Returns the status-text (e.g. "OK" or "Not Found") |
このonreadystatechange
関数は、readyStateが変更されるたびに呼び出されます。
が4でステータスが200の場合readyState
、応答の準備ができています。
例
function loadDoc() {
const 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");
xhttp.send();
}
onreadystatechange
イベントは4回(1〜4)トリガーされ、readyStateが変更されるたびに1回トリガーされます。