初始化从jQuery按钮下载的php


Initializing a php download from a jQuery Noty Button

我试图启动一个PHP下载时,按钮在jquery noty被点击。当注释应该出现时,我得到空白页,并且在firebug控制台没有错误。

var noty_id = noty({
text: 'blah',
type: 'success',
buttons: [
    {addClass: 'btn btn-primary', text: 'Download', onClick: function($noty) {
        $noty.close();
        <?php
        if (file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();
            flush();
            readfile($file);
            exit;
        }
        ?>  
    }}
]
});

没有ajax也能正常工作。我从jquery.noty.js

更改了第64行来自:

var $buttons = $('<div/>').addClass('noty_buttons');

:

var $buttons = $("<form method='post'><input type='hidden' name='download' id='download'</form>").addClass('noty_buttons');

然后在注释调用期间为隐藏字段赋值:

var noty_id = noty({
    text: 'blah',
    type: 'success',
    buttons: [
        {addClass: 'btn btn-primary', text: 'Download', onClick: function($noty) {
            document.getElementById('download').value = file;
            $noty.close();  
        }}
   ]
 });

之后,剩下的就是在表单发布后启动下载

<?php    
if(isset($_POST['download']))
{    
    $file = $_POST['download']);
    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
    }   
}
?>