首页 > 解决方案 > 在 JSON 文件中写入数据

问题描述

我有一个使用 AJAX 和 SERIALIZE 获取输入的表单。我可以获得用户输入,但我的问题是我的 PHP 代码用于将输入写入文件。

这是我的 JSON 文件。

[
    {
        "id": 1,
        "walletname": "Realtime My Salary",
        "bank": "doreming1.png",
        "icon": "generic-wallet.png",
        "currency": "US $",
        "amount": "15,935"
    },
    {
        "id": 2,
        "walletname": "Free Wallet",
        "bank": "doreming2.png",
        "icon": "generic-wallet.png",
        "currency": "JPN \u00a5",
        "amount": "5,000"
    },
    {
        "id": 3,
        "walletname": "Sample Wallet",
        "bank": "doreming3.png",
        "icon": "generic-wallet.png",
        "currency": "US $",
        "amount": "1,000"
    }
]

这是我的 PHP 代码

<?php

   $myFile = "js/data.json";
   $arr_data = array(); // create empty array

  try
  {

        //Get data from existing json file
       $jsondata = file_get_contents($myFile);

       // converts json data into array
       $arr_data = json_decode($jsondata, true);

       $id = count($arr_data) + 1;

       $icon = "generic-wallet.png";
       $amount = "12,000";

       //Get form data
       $formdata = array(
          'id'=>$id,
          'walletname'=> $_POST['"wallet-name'],
          'bank'=> $_POST['wallet-select-bank'],
          'icon'=>$icon,
          'currency'=> $_POST['wallet-select-currency'],
          'amount'=> $amount
        );

       // Push user data to array
       array_push($arr_data,$formdata);

       //Convert updated array to JSON
       $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

       //write json data into data.json file
       if(file_put_contents($myFile, $jsondata)) {
             echo "ok";
        }
       else  {
            echo "not";
       }

   }
   catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
   }

?>

AJAX

                      var a = $('#add-wallet-form').serialize();
                      $.ajax({
                        type: 'POST',
                        url: 'save.php',
                        data: a,
                        beforeSend: function() {
                        myApp.alert(a);
                        },
                        success: function(response) {
                             myApp.alert('OK');
                        },
                        error: function(response) {
                             myApp.alert('Not OK');
                        }
                      });

它在我的浏览器控制台上没有显示任何错误,我现有的 JSON 文件也没有任何反应。即使在我的 AJAX 成功和错误函数中也没有收到任何响应。

标签: phpjsonajax

解决方案


推荐阅读