前提・実現したいこと
cakephp3でhtml側に商品IDのようなものをベタで書いて、その商品情報をAPI経由で取得するようなシステムを作成したいのですが、下記のソースコードですと403エラーが出てしまいます。
https://qiita.com/nava/items/21c08bb2a7f5a4dfe65e
こちらの記事を参考にroute.phpをコメントアウトしたのですが、今度は500 (Internal Server Error)が出てしまい、解決できませんでした。
どなたか解決策を教えていただけますでしょうか。
該当のソースコード
サーバー側
ProductsController
1 public function api() 2 { 3 $this->autoRender = false; 4 if($this->getRequest()->is('ajax')) { 5 $product_id = $this->getRequest()->getData('id'); 6 $products = $this->Products->find()->where(['id IN' => $product_id])->all(); 7 $this->set(compact('products')); 8 $this->set('_serialize', 'products'); 9 } 10 }
html(ctp)側
<div id="id"> <?php $id = []; $id = [1,2,3,4,5]; $product_id = json_encode($id); ?> </div> <script> var id = []; id = <?= $product_id ?> $.ajax({ url: "products/api", type: "POST", cache: false, data: {'id': id}, dataType: 'json' }).done(function(data, textStatus, jqXHR){ //通信成功! }).fail(function(jqXHR, textStatus, errorThrown){ //通信失敗! }); </script>
###補足
script内の記述を変更した所403エラーは無くなったのですが、失敗が返ってきてしまいfailメソッドに行ってしまいます。
デバッガーを使用して確認するとサーバーへのアクセスは出来ているようです。
追記:エラー内容はerror :SyntaxError: Unexpected end of JSON inputになっています。
<script> const csrfToken = '<?= $this->getRequest()->getParam('_csrfToken') ?>'; var id = []; id = <?= $product_id ?>; $.ajax({ url: "/products/api", type: "POST", cache: false, data: {'id': id}, dataType: 'json', headers: { 'X-CSRF-Token': csrfToken } }).done(function (data, textStatus, jqXHR) { //通信成功! alert("success"); }).fail(function (jqXHR, textStatus, errorThrown) { //通信失敗! alert("error"); }); </script>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。