Vagrantのwebサーバに、ホストOSからJSONPでデータを受け取るという動作を試してみた

JSONPを参考にした本は以下です。(JSONPの説明は数ページだけです。)

https://www.amazon.co.jp/Web%E3%82%92%E6%94%AF%E3%81%88%E3%82%8B%E6%8A%80%E8%A1%93-HTTP%E3%80%81URI%E3%80%81HTML%E3%80%81%E3%81%9D%E3%81%97%E3%81%A6REST-WEB-PRESS-plus/dp/4774142042/ref=sr_1_1?ie=UTF8&qid=1525872942&sr=8-1&keywords=web%E3%82%92%E6%94%AF%E3%81%88%E3%82%8B%E6%8A%80%E8%A1%93


※ただ試したというだけなので、あてにしないでください


  • JSONP使う前に普通にfetchでリクエストした時の動作をみてみる
<!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>

f:id:okumuraa1:20180509224350p:plain

想定どおりエラーがでた。


test.phpを作成する(Vagrantで実行)

<?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>

f:id:okumuraa1:20180509231926g:plain

おー、できたできた!