質問するログイン新規登録

回答編集履歴

1

CakePHPの環境作って確かになったので引っかかるところを記載するよう修正

2018/11/16 16:18

投稿

rururu3
rururu3

スコア5545

answer CHANGED
@@ -1,7 +1,105 @@
1
- CakePHPあまり詳しくですが、
1
+ CakePHP3からControllerの階層化が面倒にったんですね・・・
2
- Appがプロジェクト名だとした
2
+ CakePHP3.6.5で試ましので引っかかった部分だけ記載していきます
3
- `http://サイト名/App/Sample/Sample1/Review/loading`では?
4
3
 
5
- ReviewControllerクラスのPHPの最初にある
4
+ bin/cake server -H 0.0.0.0 -p 5673
5
+ で試してます
6
+
7
+ routers.php
8
+ ```php
9
+ // ファイルの最後に追加(ルーティング定義しないとだめになったらしい)
6
- `Controller/Sample/Sample1/loading`
10
+ Router::prefix('Sample', function ($routes) {
11
+ $routes->fallbacks(DashedRoute::class);
12
+ });
13
+ ```
14
+ Application.php
15
+ ```php
16
+ ->add(new RoutingMiddleware($this, '_cake_routes_'));
17
+
18
+ // CSRFとりあえず面倒なのでコメント&↑部分文法合うよう;を入れる
19
+ // Add csrf middleware.
20
+ // ->add(new CsrfProtectionMiddleware([
21
+ // 'httpOnly' => true
22
+ // ]));
23
+ ```
24
+
25
+ Ajaxページ(テストとして用意したページ)
26
+ ※jquery.jsはLayoutで読み込ませるようにしてます
27
+ ```ctp
28
+ <button id="button">ボタン</button>
29
+ <script>
30
+ $("#button").on("click",function(){
31
+ var test = "test";
32
+ execAjax(test);
33
+ });
34
+
35
+ function execAjax(test){
36
+ $.ajax({
37
+ type: "POST",
38
+ url: "/sample/sample1/loading", // URLはこうなった
7
- ってなんだろう
39
+ data: {
40
+ "test" : test,
41
+ },
42
+ })
43
+ // Ajaxリクエストが成功した時発動
44
+ .done(function(response){
45
+ alert("成功");
46
+ alert(response);
47
+ })
48
+ // Ajaxリクエストが失敗した時発動
49
+ .fail(function(XMLHttpRequest, textStatus, errorThrown){
50
+ alert("失敗");
51
+ console.log("ajax通信に失敗しました");
52
+ console.log("XMLHttpRequest : " + XMLHttpRequest.status);
53
+ console.log("textStatus : " + textStatus);
54
+ console.log("errorThrown : " + errorThrown.message);
55
+ });
56
+ }
57
+ </script>
58
+ ```
59
+
60
+ Sample1Controller.php(bin/cake bake controller Sample1 --prefix Sampleで作ってloadingだけに削ぎ落とした)
61
+ ```PHP
62
+ <?php
63
+ namespace App\Controller\Sample;
64
+
65
+ use App\Controller\AppController;
66
+
67
+ /**
68
+ * Sample1 Controller
69
+ *
70
+ *
71
+ * @method \App\Model\Entity\Sample1[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
72
+ */
73
+ class Sample1Controller extends AppController
74
+ {
75
+ /**
76
+ * Initialize method
77
+ */
78
+ public function initialize()
79
+ {
80
+ parent::initialize();
81
+ $this->loadComponent('RequestHandler');
82
+ }
83
+
84
+ /**
85
+ * Loading method
86
+ * @return $test テストデータ
87
+ */
88
+ public function loading()
89
+ {
90
+ $this->autoRender = false;
91
+ if ($this->request->is('ajax')) {
92
+ // 送られてきたリクエストデータを取得する
93
+ $test = $this->request->getData('test');
94
+
95
+ // 必要な処理を実装していく
96
+
97
+ // 戻り値を返却する
98
+
99
+ echo json_encode($test);
100
+ }
101
+ }
102
+ }
103
+ ```
104
+
105
+ これで動作確認できました。