如何在客户端PC上将Javascript变量保存为文件

Ken*_*son 3 javascript php ajax file-io

我将在编辑中发布我的代码...我在提交包含代码的问题时遇到了问题.

我维护了一个聊天程序,这个程序在我被分配到它时就已经构建完了.我的工作刚开始只是为了使其与我们网站的其他部分相匹配.现在管理层正在寻求我头脑中的其他功能.一个这样的功能是客户将聊天记录的副本保存到他们的计算机的选项.

整个聊天对话存储在名为chatHistoryHTML的javascript变量中,循环使页面上的聊天会话每5秒更新一次,通过向chatHistoryHTML变量添加新行文本并将其显示在"历史"div中以供客户使用看到.

现在,我了解如何打开一个新窗口,显示聊天记录,而不显示任何徽标,背景或文本输入框.但是,我无法使用我的方法将PHP命令传递给该新页面.

理想情况下,我想要一个解决方案,允许用户单击一个按钮,并出现一个保存对话框,只保存聊天对话,而无需打开新窗口.我正在打开一个新窗口,因为我试图避免在页面上保存所有其他内容.

我愿意接受建议.我知道一点Javascript和PHP,但对AJAX一无所知

Ian*_*Ian 9

在客户端,您可以尝试:

var content, MIME_TYPE, theBlob, a;

// What will actually be put into the file
content = "THE FILE CONTENT";

// The file type
MIME_TYPE = "text/plain";
// Basically, the file itself
theBlob = new Blob([content], {type: MIME_TYPE});

// The anchor element
a = document.createElement("a");
// Set the name of the file that will be downloaded
a.download = "Chat_History.txt";
// Set the contents to be downloaded
a.href = window.URL.createObjectURL(theBlob);
// Anchor's text
a.textContent = "Download";

// What's displayed as the URL of the anchor (when hovered, copied, etc.)
a.dataset.downloadurl = [MIME_TYPE, a.download, a.href].join(":");

// Add the anchor to the page
document.body.appendChild(a);
Run Code Online (Sandbox Code Playgroud)

演示: http ://jsfiddle.net/oqskpydg/

这确实使用了并非在所有浏览器中都可用的功能,但它是一个可靠的选项.


参考文献: