admin管理员组文章数量:1244302
I want to download a JSON(or XML) file by pressing a button. In HTML I define:
<a id="exportJSON" onclick="exportJson()" class="btn"><i class="icon-download"></i> export json</a>
In JavaScipt I have following code:
function exportJson() {
var obj = {a: 123, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));
// what to return in order to show download window?
}
I found a very nice answer in Stackoveflow, but I fail to adjust it into my problem, mainly show the download window. I do not want to create another link somewhere in the page (like done in above mentioned answer, just directly show download window).
I want to download a JSON(or XML) file by pressing a button. In HTML I define:
<a id="exportJSON" onclick="exportJson()" class="btn"><i class="icon-download"></i> export json</a>
In JavaScipt I have following code:
function exportJson() {
var obj = {a: 123, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));
// what to return in order to show download window?
}
I found a very nice answer in Stackoveflow, but I fail to adjust it into my problem, mainly show the download window. I do not want to create another link somewhere in the page (like done in above mentioned answer, just directly show download window).
Share Improve this question asked Oct 16, 2014 at 21:25 BobBob 10.8k25 gold badges65 silver badges72 bronze badges 2-
1
Try changing the mime type to
application/json
– Dave Commented Oct 16, 2014 at 21:36 - It writes into the file: {"error": "Please use POST request"}. This is wrong! – Bob Commented Oct 17, 2014 at 6:01
1 Answer
Reset to default 14UPDATE
http://jsfiddle/2k4LtaLw/5/
Change your a to this
<a id="exportJSON" onclick="exportJson(this);" class="btn"><i class="icon-download"></i> export json</a>
The function
function exportJson(el) {
var obj = {
a: 123,
b: "4 5 6"
};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));
// what to return in order to show download window?
el.setAttribute("href", "data:"+data);
el.setAttribute("download", "data.json");
}
本文标签: jqueryjavascript button to download a fileStack Overflow
版权声明:本文标题:jquery - javascript button to download a file - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740207155a2241310.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论