简体   繁体   English

使用JQuery和PHP创建和下载txt文件

[英]Create and Download txt file using JQuery and PHP

I want to make an AJAX call to PHP function that creates a txt file and download it. 我想对PHP函数进行AJAX调用,以创建一个txt文件并下载它。

 if (isset($_POST["download_file"]))
{
    $filename = "sequence.txt";
    $f = fopen($filename, 'w');
    $content="q";
    fwrite($f, $content);
    fclose($f);
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Length: ". filesize("$filename").";");
    header("Content-Disposition: attachment; filename=$filename");
    header("Content-Type: application/octet-stream; "); 
    header("Content-Transfer-Encoding: binary");
    readfile($filename);
}

This is my PHP code and here is AJAX code 这是我的PHP代码,这是AJAX代码

$.ajax(
{
        url:"./apis/download_seq.php",
        data:{download_file:"true",sequence:seq},
        type: 'POST',
        success:function(data){
        }
});

And this is AJAX call. 这是AJAX调用。 Problem is that my current code saves file on server. 问题是我当前的代码将文件保存在服务器上。 Like it create sequence.txt file in directory where my PHP file is located. 像它一样,在我的PHP文件所在的目录中创建sequence.txt文件。 I want to download it to client side ie to my browser. 我想将其下载到客户端,即我的浏览器。

I am a little out from PHP but something like that for PHP side: 我对PHP有点不了解,但对于PHP方面来说有点像:

This part could be skipped: 这部分可以跳过:

$f = fopen($filename, 'w');
$content="q";
fwrite($f, $content);
fclose($f);

And if file is not huge, you can replace that with simple variable: 如果文件不是很大,则可以将其替换为简单变量:

$text = "q";
$text = $text."new text";

At the end: 在末尾:

readfile($filename);

Replace with: 用。。。来代替:

echo($text);

I DID NOT TEST THIS :) so make a test. 我没有测试:),所以​​进行测试。

For Jquery part there is a lot of answers there: Download File Using Javascript/jQuery 对于Jquery部分,有很多答案: 使用Javascript / jQuery下载文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM