fetch で POST したデータを PHP で受け取る
2019-04-09 javascript fetch php
fetch で POST して PHPで受け取るやりかた。jsonまたはFormDataを使う場合。
json で POST
js側。
fetch('./api.php', {
method : "post",
//json文字列に変換
body: JSON.stringify({name: "mgng", favorite: "cat"}),
//これが必要
headers: {"Content-Type": "application/json"}
}).then((res) => {
if(res.status !== 200) {
throw new Error("system error.");
}
return res.text();
}).then((text) => {
console.log(text);
}).catch((e) => {
console.log(e.message);
}).finally(() => {
console.log("done!");
});
php側。
<?php
$post_data = json_decode(file_get_contents("php://input"), true);
FormData で POST
js側。
let fd = new FormData();
fd.append("name", "mgng");
fd.append("favorite", "cat");
fetch('./api.php', {
method : "post",
body: fd
}).then((res) => {
if(res.status !== 200) {
throw new Error("system error.");
}
return res.text();
}).then((text) => {
console.log(text);
}).catch((e) => {
console.log(e.message);
}).finally(() => {
console.log("done!");
});
PHP側。
<?php
$post_data = $_POST;
FormData を使うと PHP側で $_POST 変数を参照できるので楽かも。
≪ 2019-04-10
うがい、手洗い、R-1
2019-04-09 ≫
もうだめだ