非同期通信でオブジェクトをJSON形式でPOSTしてPHPで受け取りたいのですがうまくいきません。
#javascript
request.js
async postData(){ const body = JSON.stringify({'hoge':1}); try{ const response = await fetch( './execute.php', { method:'POST', body:body, headers:{ 'Accept': 'application/json', 'Content-Type': 'application/json' } } ); if(!response.ok){ throw new Error('サーバーとの通信に失敗しました。'); } const json = await response.json(); if(!json.res){ throw new Error(json.err_msg); } return json; }catch(error) { alert(error); } }
#PHP
execute.php
print_r($_POST); /* ↑結果Array()となり値が格納されていないとおもわれる */
ヘッダーをapplication/x-www-form-urlencodedにして「body:'hoge=1'」とすることで値が受け取れるのを確認していますが、実際のオブジェクトがかなり深い階層構造になっており、JSON形式でPOSTできることが望ましいです。
#参考にした記事
https://developer.mozilla.org/ja/docs/Web/API/Fetch_API/Using_Fetch
https://qiita.com/legokichi/items/801e88462eb5c84af97d
回答1件
あなたの回答
tips
プレビュー