Javascript 我可以使用 jQuery 动态创建文件(及其内容)吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14121417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I use jQuery to create a file (and its content) dynamically?
提问by KAUSHIK H.S.
Here is my HTML code,
这是我的 HTML 代码,
<ul>
<li> Download <a href="#">file1</a> </li>
<li> Download <a href="#">file2</a> </li>
<li> Download <a href="#">file3</a> </li>
</ul>
I want to create something like "href=filename.txt". The "filename"of the text file and its content needs to be created dynamically based on which tag was clicked.
我想创建类似"href=filename.txt". 该"filename"文本文件及其内容的需求要创建动态地根据所单击标签。
I use a web API to get data in JSON format and hence believe security should not be an issue.
我使用 Web API 以 JSON 格式获取数据,因此认为安全性不成问题。
回答by Alexander
As of HTML5, you can use a combination of data:URLand downloadattribute. For example,
从HTML5 开始,您可以使用data:URL和download属性的组合。例如,
<a href="data:text/plain;charset=UTF-8,Hello%20World!" download="filename.txt">Download</a>
Or, programatically,
或者,以编程方式,
<a id="programatically" href="#" download="date.txt">Download</a>
$("a#programatically").click(function() {
var now = new Date().toString();
this.href = "data:text/plain;charset=UTF-8," + encodeURIComponent(now);
});?
Unfortunately, downloadattribute is not fully supportedand data:URLs are in good track.
不幸的是,download不完全支持属性并且data:URL 处于良好轨道。
Now, for a better cross-browser support you will need to create the file dynamically at server-side.
现在,为了获得更好的跨浏览器支持,您需要在服务器端动态创建文件。
回答by Moritz Petersen
You can use a data URI, this is a very simple example:
您可以使用数据 URI,这是一个非常简单的示例:
<html>
<body>
<a href="#">click</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("a").click(function() {
window.location.href = "data:text/plain;charset=UTF-8,Hello World";
});
});
</script>
</body>
</html>
You cannot set the filename, however.
但是,您不能设置文件名。

