Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript button to download a file

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

like image 509
Bob Avatar asked Dec 26 '22 03:12

Bob


1 Answers

UPDATE

http://jsfiddle.net/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");    
}
like image 173
Bojan Petkovski Avatar answered Dec 28 '22 08:12

Bojan Petkovski