【发布时间】:2020-06-01 21:45:41
【问题描述】:
我有如下所示的 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 代码在单击删除按钮时从 DOM 中删除一行。刷新页面时, 删除的行又回来了,因为一切都是通过 JSON 呈现的。
JS代码:
<script>
function removeRow(el) {
el.parentNode.remove();
}
</script>
问题陈述:
上面的 JS 代码正在从 DOM 中删除行(单击删除按钮),但在重新刷新页面时,所有内容都会再次呈现。
我想知道我需要添加什么 PHP 代码,以便在通过 JS 从 DOM 中删除行时在保存表单时从 JSON 中删除值。
第 1 步: 用户通过单击删除按钮从 DOM 中删除行。
第 2 步:在保存表单和呈现页面时,该删除的行不应该出现。
我知道我必须使用 unset 函数才能从 JSON 中删除值,但我不确定如何将它集成到表单中。
unset($data->code);
unset($data->en_desc);
【问题讨论】:
-
有兴趣使用 SESSION 将数据与页面重新加载内存分离吗?
-
我刚试了下代码,居然删了,还是没有恢复!
-
@mickmackusa 不幸的是,我过去从未使用过 SESSION。你收到我的问题了吗?
-
刚刚发布了答案。
-
我没有看到你在哪里设置
savechanges输入?
标签: javascript php json unset