我有一个PHP代码和JSON,如下所示:
PHP代码:
<?php if (!empty($_POST) && isset($_POST['savechanges']) && $_POST['savechanges'] == 1 && isset($_SESSION['pageadmin'])) {
$output = array();
$output['en_desc']=$_POST['en_desc'];
$output['code']=$_POST['code'];
$fp = fopen('../feeds/ptp-ess_landing_scommittees.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
if(file_exists('../feeds/ptp-ess_landing_scommittees.json')){
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));
}
?>
<?php if($data) { ?>
<form method="post" id="myform" style="text-align:left;">
<input type="hidden" id="savechanges" name="savechanges" value="1">
<div style="text-align:center; margin-right:9px; margin-bottom:24.703px;">
<button type="submit">Save</button>
</div>
<?php foreach ($data->code as $key => $value) { ?>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
<input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">
</div>
<?php } ?>
</form>
<?php } else { echo 'Cannot read JSON settings file'; }?>
JSON文件
:
{"code":["AEFA","AGFO"], "en_desc":["Foreign Affairs and International Trade","Agriculture and Forestry"]}
下面的DOM是通过上面的PHP/JSON代码生成的:
DOM(HTML):
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="AEFA">
<input type="text" name="en_desc[]" value="Foreign Affairs and International Trade">
</div>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="AGFO">
<input type="text" name="en_desc[]" value="Agriculture and Forestry">
</div>
下面的JS代码在单击delete按钮时从DOM中删除一行。在刷新页面时,
当所有内容都通过JSON呈现时,删除的行再次返回。
<script>
function removeRow(el) {
el.parentNode.remove();
}
</script>
问题陈述:
上面的JS代码是从DOM中删除行(单击delete按钮),但是在重新设计页面时,所有内容都会再次呈现。
我想知道我需要添加什么PHP代码,以便在通过JS从DOM删除行时在保存表单时删除JSON中的值。
用户单击delete按钮从DOM中删除行。
第二步:
保存表单并呈现页面时,删除的行不应出现。
我知道我必须使用unset函数来删除JSON中的值,但是我不确定如何将它集成到表单中。
unset($data->code);
unset($data->en_desc);