2016-11-06 188 views
1

這裏是我的代碼:爲什麼JS打開一個txt文件而不是下載它?

服務器端:

public function export(){ 
    $arr = array(); 
    if($_POST["type"] == "save"){ 
     $name = "export.txt"; 
     file_put_contents("$name",$_POST["text"]); 
     $arr["type"] = "link"; 
     $arr["url"] = "http://localhost:8000/{$name}"; 
    } 
    return $arr; 
} 

客戶端:

$(document).on('click', '#export', function() { 
    var names = ["سعید خرمی", "فرید هادوی"]; 
    var namess = names.join('\n'); 
    $.ajax({ 
     type: "post", 
     url: "/export", 
     headers: { 
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
     }, 
     data: { 
      type: "save", 
      text: namess 
     }, 
     dataType: "json", 
     success: function(data){ 
      var href = data.url; 
      window.location = href; 
     } 
    }); 
}) 

當我點擊#export(按鈕),它會打開.txt文件(而不是下載它)。事情是這樣的:

enter image description here

注意到我使用Chrome。也不會在其他瀏覽器。

我該如何強制它下載那個.txt文件?

+1

您應該使用PHP和發力下載標題。如果您直接重定向到文件URL,並且瀏覽器支持要顯示的文件類型,則它將顯示輸出而不是下載。 –

+0

瀏覽器顯示的所有內容均已下載。 – nnnnnn

+0

@nnnnnn但我需要一個'.txt'文件.. – stack

回答

2

更改您的成功部分是這樣,

success: function(data){ 
var href = download.php?filename=export.txt; 
window.location = href; 
} 

而在你的download.php:

從獲取文件名的GET變量filename(發言權$file)。

發送標題:

<?php 
$file = $_GET['filename']; // get the filename 
if (file_exists($file)) { 
    header('Content-Description: File Transfer'); 
    header('Content-Type: text/plain'); // the appropriate header type for txt file 
    header('Content-Disposition: attachment; filename="'.basename($file).'"'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize($file)); 
    readfile($file); 
    exit; 
} 
?> 

來源:PHP Readfile Documentation

+0

不需要我的PHP函數返回一些東西? – stack

+0

另外'$ file'包含了什麼?你可以寫完整的代碼嗎? – stack

+0

在$文件中,您將獲得通過Ajax發送的文件名。在答案中更新。 –

相關問題