Home  >  Article  >  Backend Development  >  Directly click on PHP to use ajax post method to download an excel file simple example

Directly click on PHP to use ajax post method to download an excel file simple example

coldplay.xixi
coldplay.xixiforward
2020-08-06 16:20:203261browse

Directly click on PHP to use ajax post method to download an excel file simple example

The example in this article describes how PHP uses ajax post method to download excel files. Share it with everyone for your reference. The details are as follows:

Project requirements, the front end initiates an ajax request, the back end generates excel and downloads it. At the same time, the token verification information needs to be included in the header. After referring to many articles, finally The implementation is as follows:

Related learning recommendations: php programming (video)

PHP backend uses base64:

$filename = 'demo.xlsx';
$objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel2007');
ob_start();
$objWriter->save("php://output");
$xlsData = ob_get_contents();
ob_end_clean();
return Api::success(['filename' => $filename, 'file' => "data:application/vnd.ms-excel;base64," . base64_encode($xlsData)]);

JS front end:

$('.download').click(function(){
    var url = "http://xxxx.com/group/bi/export";
    var params = {
      from_date: '2017-09-01',
      to_date: '2017-09-08',
      group_id: 1
    };
    $.ajax({
      type:'POST',
      url: url,
      data: params,
      beforeSend: function(request) {
        request.setRequestHeader("Authorization", "token信息,验证身份");
      },
      success: function(redata) {
        // 创建a标签,设置属性,并触发点击下载
        var $a = $("");
        $a.attr("href", redata.data.file);
        $a.attr("download", redata.data.filename);
        $("body").append($a);
        $a[0].click();
        $a.remove();
      }
    });
});

The above is the detailed content of Directly click on PHP to use ajax post method to download an excel file simple example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete