Ajax打开(post)不更新文件

Ajax open(post) does not update the file

本文关键字:更新 文件 post 打开 Ajax      更新时间:2023-09-26

我需要一个html页面,保存一些数据在服务器文件(upated_data.php)。我已经按照使用AJAX的说明进行了操作,但是服务器文件保持不变。你能帮我找到下面代码中的问题吗?

<!doctype html>
<html>
 <head><title>test</title></head>
 <body>
  <script>
   var data = '{"data": "..."}';
   xmlhttp = new XMLHttpRequest();
   xmlhttp.onreadystatechange = warn_saving;
   xmlhttp.open("POST","updated_data.php",true);
   xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
   xmlhttp.send(data);
   function warn_saving() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     alert(xmlhttp.responseText);
   }
  </script>
 </body>
</html>

我在服务器端的文件是:

-rw-r--r-- 1 www-data www-data  493 jun  5 15:42 test.html
-rw-r--r-- 1 www-data www-data    1 jun  5 15:43 updated_data.php

您试图将数据放入文件中,这不是AJAX实际做的。

如果要将数据添加到文件中,则必须使用PHP,如

$handle = fopen( 'path/to/file.txt', 'w' );
fwrite( $handle, $data );
fclose( $handle );

参考:http://www.w3schools.com/php/func_filesystem_fopen.asp

您可能必须更改$data变量以表示应该保存到文件中的方式。也许你还想改变第二个mode参数,它描述了如何处理文件以及在哪里设置指针:

w Mode =只写,并将指针指向起始,不存在则创建文件,否则删除全部内容

您的数据:Hello World

THIS IS A TEXT
^

Hello World
^

a Mode = Write only,并设置指针指向文件的END。如果文件不存在,创建一个

您的数据:Hello World

THIS IS A TEXT
              ^

THIS IS A TEXTHello World
                         ^

我希望你明白,我不能把事情的全部答案给你,但这应该极大地帮助你找到真正的方法去做,并学会理解它

感谢前面的建议,我相信我已经得到了正确的代码。现在test.html调用存储在updated_data.php中的PHP代码:

<!doctype html>
<html>
 <head><title>test</title></head>
 <body>
  <script>
   xmlhttp = new XMLHttpRequest();
   xmlhttp.open("POST","updated_data.php",true);
   xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200) 
     alert(xmlhttp.responseText);
   }
   var d = '{datos: cosa}'; 
   xmlhttp.send('data='+d);
  </script>
 </body>
</html>

和updated_data.php保存updated_data.json

<?php
   $v = $_POST['data'];
   file_put_contents('updated_data.json', json_encode($v));
?>