每次我的json文件都会覆盖ajax请求

时间:2015-05-28 08:34:12

标签: php ajax json

我尝试将我的JSON数据保存到文件中,但它只保存最后一个请求(我想每次都会覆盖我的general.json文件)。我想将所有请求添加到general.json。我的代码中的问题在哪里?

明天的ajax部分.php:

   $(document).ready(function () {

        var json = mg;
        for (var i = 0; i < json.length; i++) {

           $.ajax({
              type:"GET",
              url:"save_json.php",
              contentType: "application/json",
              dataType: "json",
              async: false,
              data: { data: JSON.stringify({
                  country: json[i][0],
                  competition: json[i][1],
                  club: json[i][2]}) },


              success: function(){ alert("data")},
              error: function(){ /*alert("error")*/}
            });
        }
    });

还有save_json.php:

  <?php
    $myFile = "general.json";
    $fh = fopen($myFile, 'w') or die("can't open file");
    $stringData = $_GET["data"];
    fwrite($fh, $stringData);
    fclose($fh)

    ?>

和general.json文件的内容:

 {"country":"America","competition":"Copa Americ","club":"Boca Juniors"}

为什么只保存最后一个请求?如何保存我的所有请求而不会每次覆盖general.json文件?

2 个答案:

答案 0 :(得分:0)

替换它:

$fh = fopen($myFile, 'w') or die("can't open file");

有了这个:

$fh = fopen($myFile, 'a') or die("can't open file");

“w”选项会删除之前文件中的内容。 “a”选项将新内容附加到文件的末尾(并保留之前的内容)。

修改

要存储有效的json字符串,请按以下步骤操作:

<?php
$json = json_decode(file_get_contents("general.json")); // here you store the decoded content of your file in a variable
$json[] = $_GET["data"]; // You append the new data to the variable
file_put_contents("general.json", json_encode($json)); // And then, you encode the whole data and put it inside the file.

以下是有关file _ * _ contents函数的文档的链接(它们替换fopen,fwrite和fclose):

答案 1 :(得分:0)

  1. 您使用了错误的模式将数据附加到文件中。您已在写入模式而不是追加模式下打开文件。
  2. 以附加模式打开文件,这样您的竞争将附加在当前文件代码中。 替换此行:
  3.   

    $ fh = fopen($ myFile,&#39; w&#39;)或死亡(&#34;无法打开文件&#34;);

    使用:

    $fh = fopen($myFile, 'a') or die("can't open file");
    
相关问题