LoginSignup
6
4

More than 3 years have passed since last update.

LaravelでJSONリクエストを受け取る

Last updated at Posted at 2020-05-17

目次

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

Laravelバージョン

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

前提条件

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

Controllerにメソッド追加

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

    public function requestJson1(Request $request)
    {
        return view('sample.requestJson');
    }

    public function requestJson2(Request $request)
    {
        $data = [
            'a' => $request->input('a'),
            'b' => $request->input('b.bb'),
            'c' => $request->input('c')['cc']
        ];
        return $data;
    }

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

viewの作成

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

requestJson.blade.php
<html>
    <head>
        <title>sample</title>
        <script type="text/javascript">
            function ajax(){

                var form = document.getElementById("sampleForm");

                var reqData = {"_token": null, "a": null, "b": {"bb": null}, "c": {"cc": null}};
                reqData._token = form._token.value;
                reqData.a = form.a.value;
                reqData.b.bb = form.b.value;
                reqData.c.cc = form.c.value;

                var req = new XMLHttpRequest();
                req.open(form.method, form.action);
                req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
                req.responseType = 'json';
                req.send(JSON.stringify(reqData));
                req.onload = function () {
                    var json = req.response;
                    alert("a:" + json['a']  + "\n" + "b.bb:" + json['b']+ "\n" + "c.cc:" + json['c']);
                }
            }
        </script>
    </head>
    <body>

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

    </body>
</html>

Laravelでjsonリクエストを受け取るようにするために
req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
を書きました
LaravelのControllerクラスはjsonを受け取るからと言って特別な記載は要りません
Content-Typeヘッダプロパティにapplication/jsonが指定されていれば、inputメソッドで値を取得できます

動作確認

http://localhost/laravelSample/sample/request-json1

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

6
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
6
4