【问题标题】:How to download CSV file from PHP script via AJAX?如何通过 AJAX 从 PHP 脚本下载 CSV 文件?
【发布时间】:2020-10-15 08:06:58
【问题描述】:

所以我想下载一个 CSV 文件,该文件由我的 PHP 文件在单击按钮时创建。

以前,这很简单,我可以说一下

<form action="working_csv.php method="post">

它会将用户重定向到“新页面”并下载我的 CSV 文件。

这是“working_csv.php”内部的样子。

I use the $_POST['location'] and $_POST['filter'] data 
earlier in the file, but it's too big of a file, so I omitted that part.

  echo "Amount of entries: ".(sizeof($myarray))."\n";

  $output = print_r($myarray, true);

  $filename = "output.csv";
  header('Content-Type: text/csv');
  header('Content-Disposition: attachment; filename="' . $filename . '"');
  header("Content-Length: " . strlen($output));
  echo $output;
  exit;

但现在,我的表单中有 2 个按钮,一个用于在屏幕上显示输出,另一个用于将相同的输出下载为 CSV 文件。

这是我 home.php 文件中当前代码的样子

  <div class="container">
    <form>      
      <h2><strong><p>Search the LDAP server</p></strong></h2>

      <label for="location"><p>Enter your search location (ex: dc=example,dc=com)</p></label>
      <input type="text" id="location" name="location" placeholder="Search Location..">

      <label for="filter"><p>Enter your search filter(s) (ex: uid=* or </p></label>
      <input type="text" id="filter" name="filter" placeholder="Filter(s)..">


      <input type="submit" name="search" id="search" value="Search LDAP Server" onclick="return chk()">

      <input type="submit" name="download" id="download" value="Download results as CSV file" onclick="return chek()">
    </form>
    <!-- Here's the AJAX call function. -->
    <p id="msg"></p>

  </div>
  <script>
    function chek()
    {
      var location=document.getElementById('location').value;
      var filter=document.getElementById('filter').value;
      var download=document.getElementById('download').value;
      var dataString={location:location, filter:filter, download:download};
      $.ajax({
        type:"post",
        url: "working_csv.php",
        data:dataString,
        cache:false,
        success: function(html){
          $('#msg').html(html);
        }
      });
      return false;
    }
  </script>

我的问题是,当我的 AJAX 函数被调用时,它只是输出结果而不是下载 CSV 文件。

【问题讨论】:

  • 我的 Ajax 代码在 home.php 部分
  • 我可能只是检测按下了哪个按钮,然后如果是下载,则在没有 ajax 的情况下加载页面。
  • 这就是问题所在。我已经内置了这个逻辑,但是当它应该下载时,它不会下载任何东西,而是输出页面上的所有数据。
  • 从下载按钮中删除onclick="return chek()",这样它就不会运行ajax 就是我的意思。将action="working_csv.php" 添加到表单标签中,当用户单击下载按钮时,它将使用表单提交而不是ajax 转到该页面。对于表单提交,搜索应该是preventDefault()。这样,Ajax 在搜索时运行,下载时提交的常规表单

标签: php jquery ajax csv


【解决方案1】:

除了我的评论之外,我会让表单能够正常提交或使用 ajax。 Ajax 搜索,正常提交下载:

<div class="container">
    <!-- Make this a proper form tag again -->
    <form id="ldap-form" method="post" action="working_csv.php">
        <h2><strong><p>Search the LDAP server</p></strong></h2>
        <label for="location"><p>Enter your search location (ex: dc=example,dc=com)</p></label>
        <input type="text" id="location" name="location" placeholder="Search Location.." />
        <label for="filter"><p>Enter your search filter(s) (ex: uid=* or </p></label>
        <input type="text" id="filter" name="filter" placeholder="Filter(s).." />
        <input type="submit" name="search" id="search" value="Search LDAP Server" />
        <input type="submit" name="download" id="download" value="Download results as CSV file" />
    </form>
    <!-- Response container -->
    <p id="msg"></p>
</div>

<script>
    $(function(){
       $('input[type="submit"]').on('click', function(e){
           // Stop form from submission
           e.preventDefault();
           // Detect button press type
           let thisSubmission   =   $(this).attr('name');
           // If the button is search, do ajax
           if(thisSubmission == 'search') {
                $.ajax({
                    type: "post",
                    url: $('#ldap-form').attr('action'),
                    data: $('#ldap-form').serialize(),
                    cache: false,
                    success: function(html){
                        $('#msg').html(html);
                    }
                });
           }
           else {
               // Just submit the form normally
               $('#ldap-form').submit();
           }
       });
    });
</script>

【讨论】:

    猜你喜欢
    • 2015-03-24
    • 2013-04-21
    • 1970-01-01
    • 2011-09-25
    • 2023-01-04
    • 2023-03-16
    • 1970-01-01
    • 2019-10-27
    • 2010-10-14
    相关资源
    最近更新 更多