How to prepare the contents of a JSON for download?

0

In a certain area of my site, the user can select a few rows from the database to export them to a JSON, after selecting all that they want an Ajax call is made to get the data of the same, however inside 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?
    }
});
    
asked by anonymous 28.03.2017 / 17:45

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();
        }
    });
    
28.03.2017 / 18:14