使用AJAX $ .post后下载(强制另存为对话框)

时间:2015-06-30 14:11:23

标签: javascript php jquery ajax

我有一个模拟终端的webapp。每个命令都使用以下脚本(部分)通过AJAX发布:

AJAX / jQuery的

$.post("sec/cmd_process.php", { n : n } )
    .done(function(data){
        output.append(display(data));
    });

如果用户在终端中键入download log,则执行以下脚本 - sec/cmd_process.php

PHP

if(isset($_POST['n'])){

    echo $_POST['n'];
    $t = explode(' ', $_POST['n']);

    if(strtolower($t[0])=='download'){
        if(!isset($t[1])) shout_error("No download specified");

        //Download Log
        elseif($t[1]=='log'){
            $stmt = $dbh->prepare("SELECT * FROM `tap_log` ORDER BY `time`");
            $stmt->execute();
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach($rows as $row) {
                $user = user_by_id($row['user']);
                $data.= "{$row['time']} - User {$user['id']} ({$user['name1']} {$user['name2']}) - {$row['information']} ({$row['subject']})".PHP_EOL;
            }

            $handle = fopen('log.txt','w+');
            fwrite($handle, $data);
                $path = 'log.txt';
                header('Content-Transfer-Encoding: binary');
                header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($path)).' GMT');
                header('Accept-Ranges: bytes');
                header('Content-Length:'.filesize($path));
                header('Content-Encoding: none');
                header('Content-Disposition: attachment; filename='.$path);
                readfile($path);
            fclose($handle);
        }
    }
}

我想要发生的是通过“另存为...”对话框下载生成的文件log.txt。如果您直接访问带有这些标头的PHP页面,此代码可以工作,但是如何通过jQuery / AJAX使其工作?

1 个答案:

答案 0 :(得分:0)

我找到的最简单的解决方案是返回一个<script>标记,将该位置转发到强制下载页面:

<script type='text/javascript'>
    location.href='sec/download.php?file=log.txt&type=text';
</script>

<强>秒/ cmd_process.php

$handle = fopen('log_'.time().'.txt','w+');
fwrite($handle, $data);
    echo "Please wait while the file downloads...";
    echo "<script type='text/javascript'>location.href='sec/download.php?file=log.txt&type=text';</script>";
fclose($handle);

<强>秒/的download.php

<?php
    $filename = $_GET['file'];
    $filetype = $_GET['type'];
    header("Content-Transfer-Encoding: binary");
    header("Last-Modified: ".gmdate('D, d M Y H:i:s',filemtime($filename))." GMT");
    header("Accept-Ranges: bytes");
    header("Content-Length: ".filesize($filename));
    header("Content-Encoding: none");
    header("Content-Type: application/$filetype");
    header("Content-Disposition: attachment; filename=$filename");
    readfile($filename);