将数据保存到使用 Ajax 以 JSON 形式发送的文本文件中

Saving data into a text file sent as JSON with Ajax

本文关键字:文本 文件 JSON 保存 数据 Ajax      更新时间:2023-09-26

我目前的代码有问题。我想使用 Ajax 将 JSON 数据发送到 PHP 脚本,但它不起作用。工作是PHP脚本可以由Ajax代码调用,但它不能将代码放入.txt文件中。我已经尝试了几件事,但我无法让它工作。(我正在尝试在.txt文件中设置用户数组)

j查询代码:

          var users = [];              
          $.ajax({
              type: "POST",
              url: hostURL + "sendto.php",
              dataType: 'json',
              data: { json: JSON.stringify(users) },
              success: function (data) {
                  alert(data);
              }
          });

PHP代码:

<?php
$json = $_POST['json'];
$data = json_decode($json);
$file = fopen('test.txt','w+');
fwrite($file, $data);
fclose($file);
echo 'Success?';
?>

你必须知道,在PHP中,json_decode会生成一个不能写入文本文件的数组。

因此,仅删除json_decode命令。

由于json_decode()函数返回一个数组,因此您可以使用将每个数组元素保存在其自己行上的file_put_contents()

<?php
  $json = $_POST['json'];
  $data = json_decode($json, true);
  file_put_contents('test.txt',implode("'n", $data));
?>