Home > Backend Development > PHP Tutorial > 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
Release: 2023-04-09 13:00:01
forward
3468 people have browsed it

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)]);
Copy after login

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>");
        $a.attr("href", redata.data.file);
        $a.attr("download", redata.data.filename);
        $("body").append($a);
        $a[0].click();
        $a.remove();
      }
    });
});
Copy after login

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!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template