JSチュートリアル

JSホーム JSの紹介 JSどこへ JS出力 JSステートメント JS構文 JSコメント JS変数 JS Let JSConst JSオペレーター JS算術 JS割り当て JSデータ型 JS関数 JSオブジェクト JSイベント JS文字列 JS文字列メソッド JS文字列検索 JS文字列テンプレート JS番号 JS番号メソッド JSアレイ JS配列メソッド JS配列ソート JSアレイの反復 JSアレイ定数 JSの日付 JSの日付形式 JS DateGetメソッド JS日付設定メソッド JS数学 JSランダム JSブール値 JSの比較 JS条件 JSスイッチ JSループFor JSループフォーイン JSループの JSループWhile JSブレイク JSIterables JSセット JSマップ JS Typeof JS型変換 JSビット単位 JS RegExp JSエラー JSスコープ JSホイスト JS厳密モード JSこのキーワード JSアロー関数 JSクラス JS JSON JSデバッグ JSスタイルガイド JSのベストプラクティス JSの間違い JSパフォーマンス JS予約語

JSバージョン

JSバージョン JS 2009(ES5) JS 2015(ES6) JS 2016 JS 2017 JS 2018 JS IE /エッジ JSの歴史

JSオブジェクト

オブジェクト定義 オブジェクトのプロパティ オブジェクトメソッド オブジェクト表示 オブジェクトアクセサー オブジェクトコンストラクター オブジェクトのプロトタイプ オブジェクト反復可能 オブジェクトセット オブジェクトマップ オブジェクトリファレンス

JS関数

関数の定義 関数パラメーター 関数の呼び出し 関数呼び出し 機能適用 関数クロージャ

JSクラス

クラスイントロ クラス継承 クラス静的

JS非同期

JSコールバック JS非同期 JSの約束 JS Async / Await

JS HTML DOM

DOMイントロ DOMメソッド DOMドキュメント DOM要素 DOM HTML DOMフォーム DOM CSS DOMアニメーション DOMイベント DOMイベントリスナー DOMナビゲーション DOMノード DOMコレクション DOMノードリスト

JSブラウザBOM

JSウィンドウ JS画面 JSロケーション JSの歴史 JSナビゲーター JSポップアップアラート JSタイミング JSクッキー

JS Web API

WebAPIイントロ WebフォームAPI Web履歴API WebストレージAPI WebワーカーAPI Web Fetch API Web Geolocation API

JS AJAX

AJAXイントロ AJAX XMLHttp AJAXリクエスト AJAX応答 AJAXXMLファイル AJAX PHP AJAX ASP AJAXデータベース AJAXアプリケーション AJAXの例

JS JSON

JSONイントロ JSON構文 JSONとXML JSONデータ型 JSON解析 JSON文字列化 JSONオブジェクト JSON配列 JSONサーバー JSON PHP JSON HTML JSON JSONP

JSとjQuery

jQueryセレクター jQuery HTML jQuery CSS jQuery DOM

JSグラフィックス

JSグラフィックス JSキャンバス JSPlotly JS Chart.js JSグーグルチャート JS D3.js

JSの例

JSの例 JS HTML DOM JSHTML入力 JSHTMLオブジェクト JSHTMLイベント JSブラウザ JSエディター JS演習 JSクイズ JS証明書

JSリファレンス

JavaScriptオブジェクト HTMLDOMオブジェクト


AJAX-XMLHttpRequestオブジェクト

AJAXの要はXMLHttpRequestオブジェクトです。

  1. XMLHttpRequestオブジェクトを作成します
  2. コールバック関数を定義する
  3. XMLHttpRequestオブジェクトを開きます
  4. サーバーにリクエストを送信する

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回トリガーされます