How to prepare the content of a JSON for download?

Asked

Viewed 448 times

0

In a certain area of my site, the user can select some rows of the database to export them to a JSON, after selecting all that want an Ajax call is made to get the data from it, but within the return how do I download it? For example:

jQuery.ajax({
    type: "POST",
    url: "seleciona-dados.php",
    data:{data: ids},
    success: function(data){
        //data já irá vir em formato JSON pelo PHP, como faço o download do mesmo para um arquivo?
    }
});
  • It would not be better to return a file from the server-side?

  • It’s an option too, as I never did, I didn’t know how to formulate the question, but I’m open to other ways too.

1 answer

1


    jQuery.ajax({
        type: "POST",
        url: "seleciona-dados.php",
        data:{data: ids},
        success: function(data){
          data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data));
          var a = document.createElement("a");
          document.body.appendChild(a);
          a.style = "display: none";
          a.href = 'data:' + data ;
          a.download = "data.json";
          a.click();
        }
    });
  • Since the user has already selected the lines and clicked on "send" I cannot open the direct link, instead of adding a link?

  • edited the code

  • @Fatasyrazer obj does not exist in this context, puts data.nome_do_objecto to return a specific property in json generated, or simply data to return the json formulated by the server.

  • osp error of writing, obj actually is data, thanks for warning, corrected !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.