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

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


概要

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.

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2024-02-12 22:08:06 RSSフィード2024-02-12 22:00分まとめ(7件)