簡體   English   中英

將數據保存到使用 Ajax 以 JSON 格式發送的文本文件中

[英]Saving data into a text file sent as JSON with Ajax

我目前的代碼有問題。 我想使用 Ajax 將 JSON 數據發送到 PHP 腳本,但它不起作用。 起作用的是 Ajax 代碼可以調用 PHP 腳本,但不能將代碼放入 .txt 文件中。 我已經嘗試了幾件事,但我無法讓它工作。 (我正在嘗試在 .txt 文件中設置用戶數組)

jQuery代碼:

          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));
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM