最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Download json object as json file using jQuery - Stack Overflow

programmeradmin4浏览0评论

I am looking for ways to download a stringfied json object as file..

I do have one solution as presented in this fiddle example:

FIDDLE

My working version looks like this

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

    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. 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>

I am looking for ways to download a stringfied json object as file..

I do have one solution as presented in this fiddle example:

FIDDLE

My working version looks like this

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

    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. 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>
Share Improve this question asked Oct 22, 2015 at 0:36 GRowingGRowing 4,71713 gold badges55 silver badges75 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 16

Try substituting "application/json" for "text/json" , calling .click() on DOM element a , removing a at click handler

$("#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./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/kda2rdLy/

发布评论

评论列表(0)

  1. 暂无评论