js 本地保存 json/txt 文件

Posted 是阿恒呀

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js 本地保存 json/txt 文件相关的知识,希望对你有一定的参考价值。

    function download(filename, text) {
            var pom = document.createElement(‘a‘);
            pom.setAttribute(‘href‘, ‘data:text/plain;charset=utf-8,‘ + encodeURIComponent(text));
            pom.setAttribute(‘download‘, filename);
            if (document.createEvent) {
                var event = document.createEvent(‘MouseEvents‘);
                event.initEvent(‘click‘, true, true);
                pom.dispatchEvent(event);
            } else {
                pom.click();
            }
        }
        var data = {
            a:11,
            b:[{a:1,b:3}]
        }
        download("data.txt",JSON.stringify(data));

通过a标签的download属性,将数据保存到href属性中,模拟点击事件实现文件下载;

href属性中也可以直接防止下载文件的地址;

以上是关于js 本地保存 json/txt 文件的主要内容,如果未能解决你的问题,请参考以下文章