将FileSaver.js saveAs()函数实现为HTML脚本

时间:2015-06-19 21:05:03

标签: javascript html blob filesaver.js

现在我正在尝试使用javascript和FileSaver.js包将信息从我正在创建的HTML页面保存到文本文档中。我不是很精通HTML,而且对javascript来说是全新的,所以很可能是我犯了一些令人震惊的错误。目前,我将eligrey的FileSaver.js文件放在与我正在使用的HTML文件相同的目录中,因此我应该能够将其简单地称为HTML中的“FileSaver.js”。

现在我正在做这样的事情:

//some irrelevant text

<script src="FileSaver.js">
  function download(){
    
    //alert("hello world");
    //this alert line was to test the function call
    //the alert actually appears when the <script> tag
    // has no src field labeled. Just an observation.
    
    var blob = new Blob(["Hello World"],{type:"text/plain;charset=utf-8"});
    saveAs(blob,"helloworld.txt");
   }
</script>

//some more irrelevant text

<input type="button" value="download" onclick="download();"/>
/*from this button I want to gather information from input text fields on the page.
 I already know how to do that, the problem is creating and, subsequently, 
downloading the text file I am trying to create. For simplicity's sake, the text I am 
capturing in this example is hardcoded as "hello world"*/

//last of irrelevant text
//oh, and don't try to run this snippet :P

我也在我的直接工作目录中提供了eligrey的Blob.js文件,以防万一。

截至目前,该按钮无效。我很确定我正在调用函数,因为我可以收到javascript警告文本,至少在脚本标记没有src时。如果我添加一个src,绝对没有任何反应。我正在测试的浏览器是Windows XP上最新的Google Chrome稳定版本(我认为是43.0)。请告诉我任何我遗失和/或做错的事。提前致谢

1 个答案:

答案 0 :(得分:1)

您无法在代码中包含src属性和内容的脚本代码。将其拆分为两个单独的脚本标记。见What if script tag has both "src" and inline script?

请注意<script> cannot be a self-closing tag

<script src="FileSaver.js"></script>
<script>
  function download(){

    //alert("hello world");
    //this alert line was to test the function call
    //the alert actually appears when the <script> tag
    // has no src field labeled. Just an observation.

    var blob = new Blob(["Hello World"],{type:"text/plain;charset=utf-8"});
    saveAs(blob,"helloworld.txt");
   }
</script>