Vagrantのwebサーバに、ホストOSからJSONPでデータを受け取るという動作を試してみた
JSONPを参考にした本は以下です。(JSONPの説明は数ページだけです。)
※ただ試したというだけなので、あてにしないでください
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <p>JSONPテスト</p> <script> fetch('http://192.168.33.10/') .then(res=>console.log('ok')) .catch(err=>console.log('err')); </script> </body> </html>
想定どおりエラーがでた。
<?php switch($_GET['user'] ?? 0){ case 1: $json = json_encode([ 'name'=>'田中', 'age'=>20, ]); break; case 2: $json = json_encode([ 'name'=>'佐藤', 'age'=>25, ]); break; default: $json = json_encode([ 'name'=>'なし', 'age'=>0, ]); break; } header("Content-type: application/x-javascript; charset=utf-8"); echo ($_GET['callback'] ?? 'func')."(${json})";
- htmlを作成(ホストOSで実行)
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <p>JSONPテスト:<span></span></p> <input type="button" value="取得"> <script> 'use strict' document.addEventListener('DOMContentLoaded',function(){ document.querySelector('[type=button]').addEventListener('click',function(){ let sc = document.createElement("script"); sc.src = "http://192.168.33.10/test.php?user=1&callback=myfunc"; document.body.appendChild(sc); },false) },false) function myfunc(json){ document.querySelector('span').innerText = `${json.name}さんは${json.age}才`; } </script> </body> </html>
おー、できたできた!