【问题标题】:Why download a csv generated by PHP with Ajax add a 0 to the end of the file?为什么用Ajax下载PHP生成的csv文件末尾加0?
【发布时间】:2019-07-25 11:20:43
【问题描述】:

这是我的代码。

从 php 生成的 CSV:

function ajax_export() {
 $strFile = "Test";
 header("HTTP/1.1 200 OK");
 header("Pragma: public");
 header("Cache-Control: must-revalidate, post-check=0, pre-check=0",false);
 header("Cache-Control: private", false);
 // nothing changes: header('Content-Type: application/download; charset=utf-8');
 header('Content-Type: text/csv; charset=utf-8');
 header("Content-Disposition: attachment; filename=\"stats.csv\"");
 // not working: header("Content-length: ".strlen($strFile));   
 echo $strFile;
 return;
}

Javascript:

$(document).on("click", '#download', function(event) {
var data = {};
$.ajax({
    url: ajaxurl, //load previous php function
    method: 'POST',
    // nothing changes dataType: 'text',
    data: data,
    success: function(response){
        console.log(response);
        var form = $('<form method="POST" action="' + ajaxurl + '">');
        $.each(data, function(k, v) {
            form.append($('<input type="hidden" name="' + k + '" value="' + v + '">'));
        });
        $('body').append(form);
        form.submit();
    }
  });
});

此代码有效,将 csv 发送给客户端进行下载。 但在 PHP 中,字符串是“Test”,而不是在控制台或下载的 csv 中,输出是“Test0”。 这个零从何而来,如何消除?

【问题讨论】:

  • 尝试使用return $strFile;,因为您可能在某处回显此函数的结果。
  • 看看调用这个函数的代码会很有用
  • @NigelRen 我已经试过了。我也尝试了 return '' 并且根本没有返回,没有任何变化。
  • @RiggsFolly 代码都在这里;我在 wordpress 里面,有一个 add_action('wp_ajax_exportstats', 'ajax_export' );没有别的了。

标签: php ajax wordpress download


【解决方案1】:

我自己找到了解决方案。 在php中,而不是return;用 die() 结束函数。 像这样:

function ajax_export() {
 $strFile = "Test";
 header("HTTP/1.1 200 OK");
 header("Pragma: public");
 header("Cache-Control: must-revalidate, post-check=0, pre-check=0",false);
 header("Cache-Control: private", false);
 header('Content-Type: text/csv; charset=utf-8');
 header("Content-Disposition: attachment; filename=\"stats.csv\"");
 echo $strFile;
 die();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多