【问题标题】:Download json object as json file using jQuery使用 jQuery 将 json 对象下载为 json 文件
【发布时间】:2016-01-21 04:08:58
【问题描述】:

我正在寻找将字符串化的 json 对象下载为文件的方法..

我确实有这个小提琴示例中提出的一种解决方案:

FIDDLE

我的工作版本是这样的

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");

如果我可以使用这个 HTML,我会更喜欢。你能建议一种方法来解决这个问题吗?

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>

【问题讨论】:

    标签: javascript jquery html json


    【解决方案1】:

    尝试用"application/json" 替换"text/json",在DOM 元素a 上调用.click(),在click 处理程序中删除a

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

    【讨论】:

    • 由于某种原因,这似乎在打开数据文件时删除了 json 字符串中的空格
    • 这个对象 {"key":"some text"} 在这个例子中像这样 {"key":"sometext"} .. "some text" 不应该合并到 "sometext" "
    • @GRowing 查看更新后的帖子。 $(this).data().obj 包裹在 encodeURIComponent() jsfiddle jsfiddle.net/kda2rdLy
    • 啊,是的,你说得对。谢谢你把你的眼睛借给我:)
    • 在 OP 的 js 中有 encodeURIComponenet() ;忽略了在上面的原始帖子中包含该部分
    猜你喜欢
    • 2016-05-26
    • 2016-08-23
    • 2018-11-01
    • 2021-08-22
    • 1970-01-01
    • 2021-11-03
    • 2017-10-25
    • 2013-11-12
    • 1970-01-01
    相关资源
    最近更新 更多