jQuery - 正在下载Textarea内容

时间:2015-10-18 14:14:06

标签: javascript jquery html

单击按钮时如何下载textarea值/内容?它应该像PHP一样:

<?php
$file = 'proxies.txt';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    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;
}
?>

我无法在这里找到任何方法来做到这一点。我不希望它再次点击一次点击下载。我只想点击一个按钮,它将下载一个包含textarea内容的txt文件。

我目前无法使用的代码:

$('#test').click(function() {
    contentType =  'data:application/octet-stream,';
    uriContent = contentType + encodeURIComponent($('#proxiescontainer').val());
    $(this).setAttribute('href', uriContent);
});

说明:

  • #test是包含按钮的a标记;
  • #proxiescontainertextarea本身;

那么如何才能让它成为textarea内容的onClick下载?

我的AJAX:

var xhttp = new XMLHttpRequest();
xhttp.open("GET", "grab.php", true);
xhttp.send();
xhttp.onreadystatechange = function() {

    if (xhttp.readyState == 4 && xhttp.status == 200) {

        var t = $('#proxiescontainer').scrollTop(), $d2 = $('#proxiescontainer').replaceWith('<button type="button" id="download" class="form-control button">Download</button><textarea id="proxiescontainer" class="form-control message-input" style="height: 250px!important;">' + xhttp.responseText + '</textarea>');

        if (t){ $('#proxiescontainer').scrollTop(t + $d2.outerHeight()); }

    }

}

1 个答案:

答案 0 :(得分:2)

使用现有的js setAttribute()不是jQuery方法;在DOM元素上使用删除jQuery()包装器

$('#test').click(function() {
    contentType =  'data:application/octet-stream,';
    uriContent = contentType + encodeURIComponent($('#proxiescontainer').val());
    this.setAttribute('href', uriContent);
});

或者使用Blob createObjectURL()download属性

&#13;
&#13;
$("button").click(function() {
  // create `a` element
  $("<a />", {
      // if supported , set name of file
      download: $.now() + ".txt",
      // set `href` to `objectURL` of `Blob` of `textarea` value
      href: URL.createObjectURL(
        new Blob([$("textarea").val()], {
          type: "text/plain"
        }))
    })
    // append `a` element to `body`
    // call `click` on `DOM` element `a`
    .appendTo("body")[0].click();
    // remove appended `a` element after "Save File" dialog,
    // `window` regains `focus` 
    $(window).one("focus", function() {
      $("a").last().remove()
    })
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea></textarea>
<button>download</button>
&#13;
&#13;
&#13;