简体   繁体   English

使用jQuery将json对象下载为json文件

[英]Download json object as json file using jQuery

I am looking for ways to download a stringfied json object as file.. 我正在寻找方法下载一个stringfied json对象作为文件..

I do have one solution as presented in this fiddle example: 我确实有一个解决方案,如这个小提琴示例中所示:

FIDDLE 小提琴

My working version looks like this 我的工作版看起来像这样

HTML HTML

    From data attribute of span:
    <span id="a-data"></span>
    <span id="obj-data" data-obj2='{"obj-1": "text-1","obj-2": "text-2","obj-3": "text-3"}'></span>

JavaScript JavaScript的

    var obj = $("#obj-data").data("obj2");
    var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));
    $('<a href="data:' + data + '" download="data.json">Download Me</a>').appendTo("#a-data");

I'd prefer if I could use this HTML. 如果我可以使用这个HTML,我更喜欢。 could you suggest a way to approach that? 你能建议一种接近的方法吗?

From data attribute of self:
<div id="data" data-obj='{"obj-1": "text-1","obj-2": "text-2","obj-3": "text-3"}'>
    Download Me
</div>

Try substituting "application/json" for "text/json" , calling .click() on DOM element a , removing a at click handler 尝试替代"application/json""text/json" ,调用.click()DOM元素a ,消除aclick处理程序

 $("#data").click(function() { $("<a />", { "download": "data.json", "href" : "data:application/json," + encodeURIComponent(JSON.stringify($(this).data().obj)) }).appendTo("body") .click(function() { $(this).remove() })[0].click() }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div id="data" data-obj='{"obj-1": "some text","obj-2": "text-2","obj-3": "text-3"}'> Download Me </div> 

jsfiddle http://jsfiddle.net/kda2rdLy/ jsfiddle http://jsfiddle.net/kda2rdLy/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM