2016-08-13 18 views
-1

觸發使用PHP文件的下載我使用的代碼How to force file download with PHP如何從JavaScript

<?php 

require('Service.php'); 
$service = new Service('config.json', getcwd() . '/..'); 
if ($service->valid_token($_GET['token']) && isset($_GET['filename'])) { 
    header('Content-Type: application/octet-stream'); 
    header("Content-Transfer-Encoding: Binary"); 
    header("Content-disposition: attachment; filename=\"" . basename($_GET['filename']) . "\""); 
    readfile($_GET['filename']); // do the double-download-dance (dirty but worky) 
} 

?> 

和使用jQuery JavaScript調用它得到

var filename = cwd + '/' + cmd.args[0]; 
$.get('lib/download.php', {filename: filename, token: token}, function(response) { 
    console.log(response); 
}); 

但該文件沒有下載。我只得到正常的ajax響應。我如何使用javascript下載文件?我需要php腳本,因爲我想下載php文件或cgi腳本。

回答

0

你不能用ajax做到這一點。您可以在指向腳本的新窗口中打開表單,並在下載準備就緒時將其關閉。

甚至使用帶有JavaScript的window.location在新窗口中打開腳本。