php - 在 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 成功和错误函数中也没有收到任何响应。
解决方案
推荐阅读
- bash - 计算所有不可删除文件的总大小(包括子目录中的文件)
- gremlin - 如何在 Gremlin 中编写条件更新语句
- java - 这个人是如何用 Java 实现图形的?
- google-chrome-extension - 为特定输入字段禁用 Microsoft 自动填充/身份验证器?
- swift - SwiftUI 应用程序不断崩溃可能是由于 ForEach
- google-apps-script - Function not executing when called second time
- python - ModuleNotFoundError:没有名为“nidaqmx”的模块
- javascript - 克隆输入字段不会将新表单克隆为空白
- amazon-web-services - 解密 AWS CodeDeploy 的配置和 appspec 路径
- dns - TLD DNS 服务器如何知道哪个权威 DNS 服务器拥有特定主机名的记录?