在Bootstrap模式确认按钮上单击,创建并下载文件jquery或knockout js

我有一个bootstrap模式(bootbox),在其上确认操作,我想创建一个包含一些数字的文件,并将文件下载为文本文件。

我已经提到在内存中创建一个文件供用户下载,而不是通过服务器,但在我的情况下它没有帮助。

这是代码:

bootbox.confirm("Item not found! Do you want to download the text file?", (yes) => { var items = response.itemNumbers; this.href = "data:text/plain;charset=UTF-8," + encodeURIComponent(items); }); 

我也试过这个:

 bootbox.confirm("item not found! Do you want to download the text file?", (yes) => { var itemNumbers = response.itemNumbers; var textFile = null; var data = new Blob([itemNumbers], { type: 'text/plain' }); // deleting old text file if (textFile !== null) { window.URL.revokeObjectURL(textFile); } textFile = window.URL.createObjectURL(data); var link = $(textFile).attr("href"); document.location.href = link; }); 

编辑:当我运行它时,第一个代码运行,没有任何反应。 第二个给出了关于Blob转换的错误:语法错误,无法识别的表达式:blob:http%3A // localhost%3A51876 / 028f2122-1646-4b2e-ae2c-2a1b588fdd8d

得到它了! 谢谢@kb。 帮助。 您提供的链接有答案。 只是发布在这里为未来的访问者:下面的代码将创建一个文件,其中包含“abcd,wxyz”和提示下载:

  var items = "abcd,wxyz"; var json = JSON.stringify(items); var blob = new Blob([json], {type: "octet/stream"}); var url = window.URL.createObjectURL(blob); window.location.assign(url); 

reference: 没有链接的JavaScript blob文件名