参考になる記事
※参考:テストコードajaxapp
※参考:JSON.stringify()の使い方と、JSONを使う理由
※参考:ajaxでInstagramの写真を抜いて上げてみる
次に調べたいこと
「ajax json」で出てきたページの内容を理解する。
https://www.sria.co.jp/blog/2014/10/lets-use-ajax-part-1-try-it-with-ajax-and-json/
https://itsakura.com/jquery-ajax
https://qiita.com/BRSF/items/e2b64416604f0ad8716a
「ajax json php」で更に深堀り
https://qiita.com/Schwl_Freiheit/items/9a01985d220d8984548b
以下2サイトの該当箇所を読んで理解する
https://ja.javascript.info/
https://jsprimer.net/
★ここからjsソースコード
html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <button id="exec">button</button> </body> <script src="app.js"></script> </html> |
js
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 45 46 47 48 49 50 51 52 |
document.getElementById('exec').addEventListener('click', function() { function update() { if(ajax.readyState === XMLHttpRequest.DONE) { if(ajax.status === 200) { $jsonData = JSON.parse(ajax.responseText); var ul = document.createElement('ul'); for (var i =0; i < $jsonData.totals.length; i++) { var li = document.createElement('li'); li.textContent = $jsonData.totals[i].location; ul.appendChild(li); } document.body.insertBefore(ul, document.body.firstElementChild); }else{ var message = request.getResponseHeader("Status"); if((message.length == null) || (message.length <= 0)){ alert("Error! Request status is "+ request.status); }else{ alert(message); } } } } var ajax = null; try { ajax = new XMLHttpRequest(); } catch (trymicrosoft) { try { ajax = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { ajax = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { ajax = null; } } } if (ajax == null) { window.alert("Error creating request object!"); } ajax.open('GET', 'ajax.php', true); ajax.onreadystatechange = update; ajax.send(null); }, false); |
php
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 |
<?php $vail = [ 'location' => 'Vail', 'boardsSold' => 100, 'bootsSold' => 100, 'bindingsSold' => 100 ]; $santaFe = [ 'location' => 'Santa Fe', 'boardsSold' => 200, 'bootsSold' => 200, 'bindingsSold' => 200 ]; $boulder = [ 'location' => 'Boulder', 'boardsSold' => 300, 'bootsSold' => 300, 'bindingsSold' => 300 ]; $denver = [ 'location' => 'Denver', 'boardsSold' => 400, 'bootsSold' => 400, 'bindingsSold' => 400 ]; $totals = [ 'totals' => [ $vail, $santaFe, $boulder, $denver ] ]; $output = json_encode($totals); echo $output; ?> |
この記事へのコメントはありません。