[英]Save array into json
我正在尝试从一个JSON文件创建一个表单,该表单可用于存储设置,以便我可以开箱即用一些看起来由数据库驱动的文件,但实际上是由文件驱动的,然后可用于设置数据库和其他设置。 我越来越近了,但不知道如何提交表格并保留每一行。 从JSON.txt中可以看到,我有一组数组,我想保存所有内容并能够添加新行。
我知道数据库驱动会更容易,但是我正在尝试在安装过程中实现这种防白痴,唯一的问题是白痴正在设置它:)需要有更多经验的人来帮助我。
JSON.txt:
[
{"Setting_Index":"Server Name","Setting_Value":"server.com"},
{"Setting_Index":"Username","Setting_Value":"name"}
]
jQuery部分:
<script type="application/javascript">
var indexValue = 0;
function existingRow(S_ID, S_NAME){
var existingRow ='<tr><td>Setting Name</td><td><input type="text" id="Setting_Index" value="'+S_ID+'"></td><TD>Value</td><td><input type="text" id="Setting_Value" value="'+S_NAME+'"></td></tr>';
$("#applyTable").append(existingRow);
}
function addRow(S_ID, S_NAME){
var addRow ='<tr><td>Setting Name</td><td><input type="text" id="Setting_Index" value=""></td><TD>Value</td><td><input type="text" id="Setting_Value" value=""></td></tr>';
$("#applyTable").append(addRow);
}
function populateRow(foo){
$(foo).each(function(i, v){
existingRow(v.Setting_Index, v.Setting_Value);
});
}
//Get json data from file to be used in functions above
$.get( "./json/load.json", function( data ) {
populateRow( data );
});
</script>
HTML:
<table width=400>
<tr><th>Setting</th><th>Value</th></tr>
</table>
<form action="" method="POST" id="saveSettings">
<table class="myTable" border="1px" style="width:400px;" >
<tbody id="applyTable">
</tbody>
</table>
<input type="text" name="Setting_Index" value="test">
<input type="text" name="Setting_Value" value="test">
<input type="submit" name="Update" id="update"/>
<input type="button" value="Add" border="1px" onclick="addRow()" />
</form>
Functions.php(试图在表单操作中使用它,已经绕了几圈)
$data = $_POST;
// $data is the posted data
// do what you want with it
$post_data = json_encode($data, JSON_FORCE_OBJECT);
$json_data = "[";
$json_data .= $post_data;
$json_data .= "]";
file_put_contents("./json/save.json.test", $json_data);
echo $json_data;
在PHP中,使用json_decode()
将json.txt文件解析为一个PHP数组。 然后,将新的$POST[]
变量附加到该数组。 最后,使用json_encode()
完整数组并重新写入文件。
另外,请确保您对$_POST
数据进行了一些验证,否则您可能会得到一些您永远不会希望用户键入的数据。
我不建议手动构建JSON对象/数组。
使用$.getJSON()
。 这样, data
是JS对象而不是字符串。 我还建议仅使用for循环而不是jQuery的each()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.