Download CSV file using “AJAX”

后端 未结 6 1007
感情败类
感情败类 2020-11-29 02:22

I\'m trying to accomplish a fairly simple task for my website, but I\"m not sure exactly how to go about it. I want the user to be viewing a table, then click a button, at w

6条回答
  •  有刺的猬
    2020-11-29 03:11

    EDIT I just tried this with a 10MB file and it seems that val() is too slow to insert the data. Hurrumph.


    Okay, so I gave this one another go. This may or may not be completely insane! The idea is to make an AJAX request to create the data, then use the callback to insert the data into a hidden form on the current page which has an action of a third "download" page; after the insertion, the form is automatically submitted, the download page sends headers and echoes the POST, and et voila, download.

    All the while, on the original page you've got an indication that the file is being prepared, and when it finishes the indicator is updated.

    NOTE: this test code isn't tested extensively, and has no real security checks (or any at all) put in place. I tested it with a 1.5MB CSV file I had laying about and it was reasonably snappy.

    Index.html

    Click Me
    

    test.js

    $(document).ready(function(){
      $("#downloadlink").click(function(){       // click the link to download
          lock();                                // start indicator
          $.get("create.php",function(filedata){ // AJAX call returns with CSV file data
              $("#filedata").val(filedata);      // insert into the hidden form
              unlock();                          // update indicator
              $("#hiddenform").submit();         // submit the form data to the download page
          });
      });
    
      function lock(){
          $("#wait").text("Creating File...");
      }
    
      function unlock(){
          $("#wait").text("Done");
      }
    });
    

    create.php

    
    

    download.php

    
    

提交回复
热议问题