概要
fetch APIを使ってjson形式のデータをPOSTしてPHPで受け取るやり方について。
環境
PHP
# php -v
PHP 7.2.11 (cli) (built: Oct 16 2018 00:40:40) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.2.11, Copyright (c) 1999-2018, by Zend Technologies
実装
js
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"id": "01",
"title": "テスト01",
})
})
.then(response => {
return response.json();
})
.then(json => {
console.log(json);
})
.catch(e => {
console.error(e);
});
PHP
$params = json_decode(file_get_contents('php://input'), true);
$id = $params["id"];
$title = $params["title"];
参考
[フロントエンド] fetchを用いたAjax通信を行う
fetch API でも POST したい!
Using the Fetch API to send and receive JSON with PHP.