Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/230.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 写入文件并立即发送AJAX响应_Php_Jquery_Ajax - Fatal编程技术网

Php 写入文件并立即发送AJAX响应

Php 写入文件并立即发送AJAX响应,php,jquery,ajax,Php,Jquery,Ajax,更新: 我使用另一种解决方案将数据写入文件。在AJAX等待响应时,我似乎无法回显数据。所以我现在使用fwrite $fileHandle = ''; $fileHandle = fopen("export.txt","w"); fwrite($fileHandle, $export); 原件: 你好, 也许我的逻辑是错的。 我通过AJAX调用从另一个URL获取数据。 到目前为止,这是有效的 但是现在我还想添加一个文件导出 $handler = new MyHandler(); // Step

更新:

我使用另一种解决方案将数据写入文件。在AJAX等待响应时,我似乎无法回显数据。所以我现在使用fwrite

$fileHandle = '';
$fileHandle = fopen("export.txt","w");
fwrite($fileHandle, $export);

原件:

你好, 也许我的逻辑是错的。 我通过AJAX调用从另一个URL获取数据。 到目前为止,这是有效的

但是现在我还想添加一个文件导出

$handler = new MyHandler();
// Step 1: get data from URL
$dataAjax = $handler->getData($_POST['data']);
// Step 2: write the data into a text file to provide a download
$handler->writeToText($dataAjax);
echo json_encode($dataAjax);
现在控制台向我显示了一个“parserError”,因为我的JSON数据还包含我想要写入文件的字符串。这是不好的,不需要的。 下面是我想如何将数据写入txt文件的测试:

function writeToText($data)
{
   header("Content-type: text/plain");
   header("Content-Disposition: attachment; filename=export.txt");
   header("Pragma: no-cache");
   header("Expires: 0");
   $title = "";
   $title .= "Name,Quantity,Model,Price,Weight,Status"."\n";
   echo $title;
}
这就是错误的样子:

{
    "readyState": 4,
    "responseText": "Name,Quantity,Model,Price,Weight,Status\n[{\"domain\":\"Text\",\"name\":\"Banana\}]",
    "status": 200,
    "statusText": "OK"
} 
 parsererror

那么,您希望下载的文件是什么,
json
还是
csv
,因为它看起来像是两者的混合。没有混合。正如您所看到的,内容类型是text/plain,字符串只是一个列表。parsererror演示了浏览器如何解释接收到的数据。浏览器接收JSON,但文件将以纯文本形式写入。我明白了。我注意到的另一件事是,在
writeToText
函数中,您正在接受一个参数
$data
,但您没有处理它。是代码丢失了还是忘记添加了?不,没关系。正如我所写的,这个函数是一个演示。我现在发送数据,但是对于这个示例,我使用了一个修复示例来测试它。您可以粘贴调用ajax函数的代码吗?