Fetch APIを利用してGETおよびPOSTメソッドによるAjax通信をおこなってみます。
GET
index.html上のフォームからtest-get.phpに値を渡して処理し、index.htmlの<div id=”result”></div>に返ってきた値を表示させています。
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<!DOCTYPE html> <head> <meta charset="utf-8"> </head> <html> <body> <form> <input id="word1" type="text" name="word1" /> <input id="word2" type="text" name="word2" /> <input id="button" type="button" value="送信" /> </form> <div id="result"></div> <script> document.getElementById('button').addEventListener('click', function (e) { let params = new URLSearchParams(); params.set('word1', document.getElementById('word1').value); params.set('word2', document.getElementById('word2').value); fetch('test-get.php?' + params.toString()) .then(function (response) { console.log(response.headers.get('Content-Type')); //text/html; charset=UTF-8 console.log(response.headers.get('Date')); //Wed, 16 Jan 2019 03:08:21 GMT console.log(response.status); //200 return response.text(); }) .then(function (data) { document.getElementById('result').textContent = data; }) .catch(function (error) { document.getElementById('result').textContent = error; }) }, false) </script> </body> </html> |
25〜37行目
fetch()はpromiseを返します。処理が正常に実行されるとthenが実行されます。Responseオブジェクト(上記ではresponse)にはリクエストして返ってきたレスポンスメッセージ(HTTPレスポンス)が含まれています。例えばResponseオブジェクトのheadersプロパティでHTTPヘッダーの情報を確認できます(27、28行目)。
test-get.phpからはレスポンスとしてテキストデータが返ってきます。Responseオブジェクトのtext()メソッドでレスポンスボディにアクセスし、2番目のthen(32行目)でその具体的なデータを処理しています。もしJSONが返ってくるならばjson()を利用します。
関連ページ
test-get.php
1 2 3 4 5 6 |
<?php $word1 = htmlspecialchars($_GET['word1'], ENT_QUOTES, 'UTF-8'); $word2 = htmlspecialchars($_GET['word2'], ENT_QUOTES, 'UTF-8'); echo "{$word1}と{$word2}を入力しました。"; |
POSTおよびGETメソッドについては下記関連ページをご覧下さい。
関連ページ
入力フォームを作成しデータを次の画面に送る [POSTメソッド][GETメソッド]
POST
フォームからPOSTで値を送ります。
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!DOCTYPE html> <head> <meta charset="utf-8"> </head> <html> <body> <form id="form"> <input id="word1" type="text" name="word1" /> <input id="word2" type="text" name="word2" /> <input id="button" type="button" value="送信" /> </form> <div id="result"></div> <script> document.getElementById('button').addEventListener('click', function (e) { let data = new FormData(document.getElementById('form')); fetch('test-post.php', { method: 'POST', body: data, }) .then(function (response) { return response.text(); }) .then(function (data) { document.getElementById('result').textContent = data; }) .catch(function (error) { document.getElementById('result').textContent = error; }) }, false) </script> </body> </html> |
24、25行目
リクエストのための情報をオプションとして設定しています。methodパラメータには POST、PUT、DELETEなどの様々なリクエストを設定できます。デフォルトではGETに設定されています。bodyパラメータにはリクエストボディーを設定します。
もしJSONデータをPOSTする場合には下記のようにオプションを設定します。
1 2 3 4 5 6 7 8 9 |
let data = { name: 'tarou' }; fetch('hoge.php', { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } }) |
test-post.php
1 2 3 4 5 6 |
<?php $word1 = htmlspecialchars($_POST['word1'], ENT_QUOTES, 'UTF-8'); $word2 = htmlspecialchars($_POST['word2'], ENT_QUOTES, 'UTF-8'); echo "{$word1}と{$word2}を入力しました。"; |
参照文献