LoginSignup
0
1

More than 1 year has passed since last update.

JavaScriptからPHPにデータを渡してjsonで保存する

Posted at

クライアントからの情報をサーバーに残しておきたい。
でもデータベースを使うほどのものでもない。
そんな時は配列としてjsonでファイルを保存してしまう。

script.js
async function save(num1, num2){
    let req = await fetch("./save.php",{
        method: "post",
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify([num1,num2]),
    });
}

save(2,1);
save.php
<?php
    $postData = json_decode(file_get_contents("php://input"),true);//jsからjson受け取り
    file_put_contents("./data.json", json_encode($postData));//jsonファイルを保存
?>

保存したjsonは頑張れば見られるし、リファラーのチェックとかも必要なので注意。

0
1
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
0
1