我可以通过简单的代码轻松地将数据导出为excel,但是当我需要调用export.php时我遇到的问题是j查询代码数据不能下载为export.php文件代码,如下所示
<?php
include '../../config.php';
function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
$str = mb_convert_encoding($str, 'UTF-16LE', 'UTF-8');
}
$filename = "website_data_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv<span>; charset=UTF-16LE</span>");
$out = fopen("php://output", 'w');
$flag = false;
$result = mysql_query("SELECT * FROM employee") or die('Query failed!');
while(false !== ($row = mysql_fetch_assoc($result))) {
if(!$flag) {
fputcsv($out, array_keys($row), ',', '"');
$flag = true;
}
array_walk($row, 'cleanData');
if($row['photo']!='')
{
$row['photo']="http://localhost/admin/employee_image/".$row['photo'];
}
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
有什么方法可以通过jquery调用这个文件吗?
答案 0 :(得分:1)
不,你不能通过Javascript使用jQuery或任何其他库来实现这一点,AJAX在浏览器内的Javascript引擎中调用数据。
但您可以使用HTML5下载属性:
<a href="your_file.xls" download="YourFile.xls">Download Excel</a>
并在PHP中提供正确的标题:
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=your_file.xls");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
编辑:
虽然上述方法有效,但我发现这一点后,我会回答:
http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
由https://stackoverflow.com/users/455556/john-culviner制作,如果您需要,请向他寻求帮助
干杯!