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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:46:57  来源:igfitidea点击:

Can I use jQuery to create a file (and its content) dynamically?

javascriptjqueryajaxhtml

提问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:URLdownload属性的组合。例如,

<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);
});?

See it here.

看这里。

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.

但是,您不能设置文件名。