Implementation code for Jquery ajax requesting export of Excel table

  • 2021-06-28 10:04:36
  • OfStack

Paste code directly


$("#btn-export").click(function(){
  var exportExcel = "export_excel";
  dataParams[exportExcel] = 1;
  var params = $.param(dataParams);
  var url = host+"&"+params;
  $('<form method="post" action="' + url + '"></form>').appendTo('body').submit().remove();
  delete dataParams[exportExcel];
});

Simple instructions 1:

Usage scenario: ajax requests the server to return json data, and a new requirement arises to export the returned json to an excel table.

In the above code, dataParams is the request parameter for ajax, which is an object of type Object defined earlier. Because the request parameter is not fixed, the request parameters are placed in the object.

We know that the ajax request server is not able to return the excel table (I'm not sure, if the reader can export it, post it, we'll learn together). We need to convert the request to a page request, that is, to an form form to send the request, so we can export the data to a table and have the following code:


$('<form method="post" action="' + url + '"></form>').appendTo('body').submit().remove();

To keep the page clean and tidy, remove the form form that submitted the request from the page after sending the request.


Related articles: