从ajax文章的内容创建一个文件

Create a file from content of ajax post

本文关键字:一个 文件 创建 文章 ajax      更新时间:2023-09-26

我想要一个php脚本,它可以根据ajax文章的内容创建一个文件。要调用的文件report.txt

我有这个php脚本,位于/var/www/copypast.test/public_html/index.php

<?php
 header('Access-Control-Allow-Origin: *');
 $report = $_POST['report'];
 echo $report;
 $report_file = fopen("report.txt", "w");
 fwrite($report_file, $report);
?>

我现在有一篇简单的ajax文章,其中包含一些测试文本

 var text = 'test string';
 var formData = new FormData();
 formData.append('report', text);
 var ajax = jQuery.ajax({
  type: "POST",
  url: 'http://copypaste.test',
  data: formData,
  dataType: 'text',
  processData: false, 
  contentType: false,
    success: function(){ 
      console.log('success'); 
    },
    error: function() {
     console.log('error'); 
    } 
  });
 }

ajax帖子是成功的,因为我在响应中得到了test string,这在我的控制台中

 readyState 4
 responseText "'ntest string"
 status  200
 statusText "OK"

当我转到http://copypaste.test时,我在进入目录时看不到文本或文件的创建?

有人能告诉我正确的方向吗?

感谢

我注意到,您在写入后从未调用fclose("report.txt")来关闭文件。这可能会造成问题。

您可以使用此函数调用来处理文件的打开、写入和关闭。

  file_put_contents("report.txt",$report);

您可以尝试替换上面函数调用中的"report.txt",以防文件仍在内存中打开,并且您无法访问它。