单击按钮时如何下载文本区域值/内容?它应该像 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;
}
?>
我在这里找不到任何方法来做到这一点。我不希望它制作一个 href 来第二次点击下载。我只想单击一个按钮,它将下载一个包含文本区域内容的 txt 文件。
我当前无法运行的代码:
$('#test').click(function() {
contentType = 'data:application/octet-stream,';
uriContent = contentType + encodeURIComponent($('#proxiescontainer').val());
$(this).setAttribute('href', uriContent);
});
解释:
#test
是包裹按钮的a
标签;#proxiescontainer
是textarea
本身;
那么我怎样才能让它成为文本区域内容的点击下载呢?
我的 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()); }
}
}
最佳答案
使用现有的 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
属性
$("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()
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea></textarea>
<button>download</button>
关于javascript - jQuery - 下载 Textarea 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33198936/