【发布时间】:2018-07-20 16:48:28
【问题描述】:
假设服务器上的 JSON 文件包含 ['one','two','three']。
如果发生 HTML 按钮单击事件并且变量设置为“二”,
如果 num 变量值与 JSON 文件中的“二”匹配,如何使用 HTTP 请求和 PHP 从 JSON 文件中删除“二”?
更新!!!按钮点击后返回相同的值
文件(JS & HTML):
$('#button1').click(function() {
let num = 'two';
$.ajax({
type: "POST",
url: "./update.php",
data: num
});
});
<html>
<head>
<title>Button Writer</title>
</head>
<body>
<button id="button1" type="button">Write to File</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="./app.js"></script>
</body>
</html>
JSON 文件: (codes.json)
["one","two","three"]
PHP 文件(update.php)
<?php
$jsonContents = file_get_contents('./codes.json');//Read here the json file into text
$array = json_decode($jsonContents);
$value = $_POST;
if (($key = array_search($value, $array )) !== false) {
unset($array [$key]);
}
$jsonString = json_encode($array);
//Here you can save the content of $jsonString into the file again
file_put_contents("./codes.json", $jsonString);
echo $jsonString;
?>
【问题讨论】:
-
"如果这个值匹配 2" ...你在说什么值?以及您想用新更改的 JSON 做什么?把它放回文件中?
-
@Iwrestledabearonce。我的意思是发送一个 HTTP 请求变量 num 的值,以便在匹配的情况下从 JSON 文件中拼接出“两个”。
-
什么变量的值?
-
@Iwrestledabearonce。看一下 JS 文件。让 num = '两个';按钮点击事件
标签: javascript php jquery html xmlhttprequest