2016-11-06 187 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发送的文件名。在答案中更新。 –

相关问题