LoginSignup
5
8

More than 5 years have passed since last update.

fetch APIでJSONをPOSTしてPHPで受け取る

Posted at

概要

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"];

参考

github/fetch
Fetch
Fetch 概説

[フロントエンド] fetchを用いたAjax通信を行う
fetch API でも POST したい!
Using the Fetch API to send and receive JSON with PHP.

5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8