我有一个包含数据对象的标签,如下所示:
<a class="export-json" data-button="[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]">Export json</a>这些值通过data-button传递,如下所示:
$(".export-json").attr("data-button", data);data是一个包含json的列表。
数据是这样的:
[{
name: "John",
position: "663",
a: 15,
b: 48
},
{
name: "311",
position: "663",
a: 12,
b: 48
}]因此,我希望转换该数据对象并将其作为JSON文件下载。
$(".export-json").click(function(){
var data = $.parseJSON($(this).attr('data-button'));
exportJson(this, data);
});
function exportJson(element, data) {
var results = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data));
element.setAttribute("href", "data:"+results);
element.setAttribute("download", "data.json");
}如果我因为这里的这个parseJSON而喜欢这个$.parseJSON($(this).attr('data-button')),我会得到:
Uncaught SyntaxError: Unexpected token o in JSON at position 1如果我删除parseJSON,当我下载该文件时,我会看到以下内容:
"[object Object],[object Object],[object Object],[object Object],[object Object]"我不知道为什么会发生这种事?
如果我浏览数据,所有内容都被正确打印出来:
for (var i = 0; i < data.length; i++) {
var item = data[i];
console.log(item);
}有没有人能帮帮我
发布于 2016-09-26 07:11:36
使用jQuery data()方法而不是attr()
更改:
$(".export-json").attr("data-button", data)至:
$(".export-json").data("button", data)然后,它将被存储为数组,不需要任何解析
如果您确实需要在属性中使用该属性,则需要首先将数组字符串化,然后再将其赋值为属性值
https://stackoverflow.com/questions/39692237
复制相似问题