ป้ายกำกับ: เอแจ็กซ์

jQuery ajax download filejQuery ajax download file

มีวิธีที่ง่ายกว่า Fetch API: Download

งานที่ทำอยู่วันนี้ ต้องส่งข้อมูลไปให้อีกไฟล์เพื่อสร้างไฟล์ excel ให้ดาวน์โหลด แต่เพราะว่าจำเป็นต้องส่งรายการ ที่เลือกไปให้ด้วย บางครั้งมันยาวเกินกว่าที่จะส่งไปแบบ GET ทำให้ต้องส่งแบบ post และไม่อยากจะใช้วิธี submit form ไปอีกหน้าเพราะว่าหน้านี้เป็นแบบใช้ ajax ทั้งหมด ปัญหาคือ jquery ajax มันไม่รองรับการ download file จริง ๆ ถ้าจะทำก็ทำได้ แต่เขียนยุ่งยากมาก แต่ก็มีคนเขียน jquery.fileDownload ทำให้ทำได้ง่าย ๆ มาก ๆ แค่ใส่ url ไปแค่นั้นเอง

<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <title>jquery.fileDownload</title>
  <link href="vendor/components/jqueryui/themes/base/jquery-ui.min.css" rel="stylesheet" type="text/css" />
 </head>
 <body>
  <button id="downloadBtn" type="button">Download with dialog</button>
  <hr>
  <button id="downloadBtn1" type="button">Download without dialog</button>
  <hr>
  <form action="PHPExcel_writer_styles_border.php" id="formA" method="post">
   <label>Search :
   <input name="search" type="text"></label>
   <button type="submit">Download with form</button>
  </form>
  <script src="vendor/components/jquery/jquery.min.js"></script>
  <script src="vendor/components/jqueryui/jquery-ui.min.js"></script>
  <script src="vendor/johnculviner/jquery.fileDownload/src/Scripts/jquery.fileDownload.js"></script>
  <script>
   $(function() {

    $('#downloadBtn').click(function(event) {
     event.preventDefault();

     $.fileDownload('PHPExcel_writer_styles_border.php', {
      failMessageHtml: "There was a problem generating your report, please try again.",
      preparingMessageHtml: "We are preparing your report, please wait...",
     });

    });

    $('#downloadBtn1').click(function(event) {
     event.preventDefault();

     $.fileDownload('PHPExcel_writer_styles_border.php');

    });

    $('#formA').submit(function(event) {
     event.preventDefault();

     $.fileDownload($(this).prop('action'), {
      data: $(this).serialize(),
      failMessageHtml: "There was a problem generating your report, please try again.",
      httpMethod: "POST",
      preparingMessageHtml: "We are preparing your report, please wait...",
     });

    });

   });
  </script>
 </body>
</html>