4
4

More than 3 years have passed since last update.

LaravelでJSONを返す

Last updated at Posted at 2020-05-10

目次

Laravelの記事一覧は下記
PHPフレームワークLaravelの使い方

Laravelバージョン

動作確認はLaravel Framework 7.19.1で行っています

前提条件

eclipseでLaravel開発環境を構築する。デバッグでブレークポイントをつけて止める。(WindowsもVagrantもdockerも)
本記事は上記が完了している前提で書かれています
プロジェクトの作成もapacheの設定も上記で行っています

Controllerにメソッド追加

(1) /sample/app/Http/Controllers/SampleController.phpにjson1メソッド、json2メソッドを追記

    public function json1(Request $request)
    {
        return view('sample.json');
    }

    public function json2(Request $request)
    {
        $data = [
            'a' => $request->input('a'),
            'b' => $request->input('b')
        ];
        return $data;
    }

配列をreturnするようにします

(2) /sample/routes/web.phpに下記を追記
Route::get('sample/json1', 'SampleController@json1');
Route::post('sample/json2', 'SampleController@json2');

viewの作成

/sample/resources/views/sample/json.blade.phpファイル作成

json.blade.php
<html>
    <head>
        <title>sample</title>
        <script type="text/javascript">
            function ajax(){
                var form = document.getElementById("sampleForm");
                var req = new XMLHttpRequest();
                req.open(form.method, form.action);
                req.responseType = 'json';
                req.send(new FormData(form));
                req.onload = function () {
                    var json = req.response;
                    alert("a:" + json['a'] + "\n" + "b:" + json['b']);
                }
            }
        </script>
    </head>
    <body>

        <form id="sampleForm" action="{{ url('sample/json2') }}" method="post"  onsubmit="ajax(); return false;">
            @csrf
            <input type="text" name="a" >
            <input type="text" name="b" >
            <input type="submit" >
        </form>

    </body>
</html>

動作確認

http://localhost/laravelSample/sample/json1

インプットフォームに値を適当に入力して送信ボタンをクリック
インプットフォームに入力した値がalertで表示された

a.png

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4