weixin_33724570 2016-03-23 19:20 采纳率: 0%
浏览 69

Ajax下载文件错误

I have content that JS creates in a function and i need to print that content into my downloads folder but when i try to via ajax it will not work and is not throwing any errors

JS code

$.ajax({
      url: 'includes/download.php',
      type: 'post',
      data: {'filename': name_file, 'content': content},
      success: function(data, status) {
        if(data == "ok") {
          console.log('data okay');
        }
      },
      error: function(xhr, desc, err) {
        console.log(xhr);
        console.log("Details: " + desc + "
Error:" + err);
      }
    });

PHP code

<?
$filename = $_POST['filename'];
$content = $_POST['content'];

header("Content-type: csd/");
header("Content-Disposition: attachment; filename=".$filename);

print $content;
  • 写回答

1条回答 默认 最新

  • weixin_33695450 2016-03-23 19:49
    关注

    If you have the content in a javascript variable you don't need any ajax call to save it

    var content = 'anything';
    var filename = 'testFile.txt';
    var hiddenElement = document.createElement('a');
    
    hiddenElement.href = 'data:attachment/text,' + encodeURI(content);
    hiddenElement.target = '_blank';
    hiddenElement.download = filename;
    hiddenElement.click();
    

    The filename variable should contain the extension as well

    JsFiddle

    评论

报告相同问题?