XMLHttpRequestでデータの送受信 - JavaScript
XMLHttpRequestというオブジェクトを使うことによって、ページを更新しなくても、ページ内のデータを反映することができる
ツイキャスのコメビュに使えそうだから、少し使ってみた
今回やったことは「ページ表示時にサーバーへリクエストし、サーバーでJSON形式のデータを返し、ブラウザコンソールに表示」
また、サーバーにはPythonのBottleを使った
コード
クライアント側のindex.html
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>非同期処理</title> <script> const xhr = new XMLHttpRequest(); xhr.open('GET', 'http://localhost:3000/ajax_test?date=20180330', true); xhr.send(); xhr.onreadystatechange = () => { if(xhr.readyState === 4 && xhr.status === 200) { console.log( JSON.parse(xhr.responseText) ); } } </script> </head> <body> <div>テスト</div> </body> </html>
次にサーバー側のserver.py
from bottle import request, route, run, template import json @route('/') def index(): # index.htmlの表示 return template('index') @route('/ajax_test') def ajax_test(): # クエリの取得 queryDate = request.query.date # レスポンスの作成 resDict = { 'name': 'tamago', 'age': '20', 'date': queryDate } # JSON形式に変換し、返す return json.dumps(resDict) run(host='localhost', port=3000, debug=True)
pipenv python3 server.py
でサーバーを起動して、http://localhost:3000/
にアクセスしてみると、ブラウザのコンソールに値が表示された!!!
ポイント
new XMLHttpRequest
でオブジェクト生成open()
でリクエストの準備send()
でリクエストの開始onreadystatechange
にレスポンスへの処理を記述if(xhr.readyState === 4 && xhr.status === 200)
でレスポンスが正しく取得できる状態か確認する
サーバー側には触れないでおく
XMLHttpRequest
XMLHttpRequestオブジェクトの生成
const xhttp = new XMLHttpRequest();
XMLHttpRequestのメソッド
- open
- send
open(method, url, async, user, pass)
xhr.open('GET', 'http://localhost:3000/ajax_test?date=20180330', true);
リクエストの設定を行う
XMLHttpRequest.open(method, url, async, user, pass)
- method:
GET
かPOST
のリクエストタイプ - url: ファイルの場所
- async: 同期(
false
)か非同期(true
)か
meghod
に指定する値のGET
はサーバーからデータを受け取るときに使い、POST
はクライアントからサーバーに送るときに使う。
url
に指定できる値はhttp
で始まる値なのかな?(よくわかっていない)こちら のサイトに書いてあった
データの送信にはURL内に?キー=値
とする
例)'http://localhost:3000/ajax_test?date=20180330'
send()
xhr.send();
XMLHttpRequest.send()
open()でGET
を指定した場合のリクエスト送信
XMLHttpRequestのプロパティ
- onreadystatechange
- readystate
- state
onreadystatechange
XMLHttpRequest.onreadystatechange
リクエストがレスポンスが返ってきたとき、実行される関数を定義できる
readyStateの値が変わるたびに呼ばれるらしい関数を代入する
const xhttp.onreadystatechange = () => { if (this.readystate == 4 && this.state == 200){ ... } }
readystate
XMLHttpRequest.readystate
XMLHttpRequestのステータスを持つプロパティ
値 | 説明 |
---|---|
0 | リクエストが初期化されていない |
1 | サーバーとの接続成功 |
2 | リクエストを受け付けた |
3 | リクエストの処理中 |
4 | リクエストが終了、レスポンスの準備完了 |
state
XMLHttpRequest.state
レスポンスのステータス番号を返す
200, 404 など
readystate
が4
で、state
が200
の場合、レスポンスの準備が完了している
レスポンスの準備が完了するまでにonreadystateの関数が4回呼ばれることになる