2

Similar question to this: Download a file by jQuery.Ajax.

There is my code:

    function saverequest(url, data) {
    var response = $.ajax({
        url: url,
        timeout: requestTimeout,
        global: false,
        cache: false,
        type: "POST",
        data: data,
        dataType: "json",
        success: function () {
            var blob = new Blob([response.data], {type : 'application/json'});
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = "export.json";
            link.click();
        }
    });

    return response;
}

asd

As i see in this picture, server-side responding with normal json data file.

But this code saving export.json file with "underfined" content inside.

There is a question: how to write data from response to blob object?

hedw1q
  • 35
  • 5

1 Answers1

3

The issue is because you're using the response variable, which holds the jqXHR object returned from the $.ajax() call. This object does not have a data property, hence you see undefined in the output.

Given the pattern you're using, you should define an argument in the success handler function which receives the JSON data in the request, and then use that instead. Try this:

function saverequest(url, data) {
  return $.ajax({
    url: url,
    timeout: requestTimeout,
    global: false,
    cache: false,
    type: "POST",
    data: data,
    dataType: "json",
    success: function(data) { // note 'data' here
      var blob = new Blob([data], {
        type: 'application/json'
      });
      var link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = "export.json";
      link.click();
    }
  });
}

Also note that, depending on the browsers you need to support, you may need to append the link element to the DOM before the click event can be raised on it.


Using this code I get [object Object] in the export.json file

This would be because the JSON holds an object, not an array as the Blob() constructor expects. To fix this provide the data in the href as plain text instead:

// change the AJAX request to retrieve the JSON as text (without deserialisation)
dataType: 'text'

// amend the href of the link to use text instead of a Blob
link.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339