【问题标题】:How to delete value from JSON file with HTTP request and PHP?如何使用 HTTP 请求和 PHP 从 JSON 文件中删除值?
【发布时间】: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


【解决方案1】:

然后在服务器上,你可以:

$jsonContents = file_get_contents('path/to/file.json'); //Read here the json file into text
$array = json_decode($jsonContents);

$value = $_POST["num"];

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('path/to/file.json', $jsonString);

【讨论】:

  • +1 如果你把第一行改成$jsonContents = file_get_contents('path/to/file.json'); // comment... 这样PHP就不会抛出语法错误
  • @Tyblitz 我更改了第一行并尝试写入文件 file_put_contents("./codes.json", $jsonString); 但 JSON 文件中的值仍然返回相同。检查我上面的 PHP 代码的内容,看看我是否做错了
  • @claOnline 代码是有效的,除了你应该删除$array [$key]之间的空格。如果不是这样,您可能有服务器权限问题(检查PHP function chmod),请尝试在file_put_contents 之前执行chmod('./code.json', 0755)
  • @Tyblitz。是否所有内容都删除了空间并添加了 chmod 功能。它仍然不起作用。仍然返回 ["one","two","three"] 而不是 ["one","three"] 无论如何,我正在 Windows 10 pc 上使用 XAMPP 进行测试。
  • @claOnline 检查所有其他可能的故障点。您的 AJAX 调用是否成功,PHP 是否响应等?无论如何,这超出了您原始问题的范围,您可能应该通过接受它来向社区表明这个答案是正确的,因为它确实回答了标题中的问题。
猜你喜欢
  • 2019-02-02
  • 1970-01-01
  • 1970-01-01
  • 2020-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多