0

将值从 javascript 文件发送到服务器端 php 文件,并使用 jquery ajax post 方法在服务器端创建一个文件。

尝试一些代码

javascript代码

  $.ajax({
    type: "POST",
    url: "http://localhost/export/some.php",
    data: { dataString: "hi" },
    cache: false,
    success: function(){
      alert(dataString);
      this.openDestinationURL();
    }
  });

php代码如下

 header("Pragma: public");
 header("Expires: 0"); 
 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
 header("Content-Type: text/x-csv");
 header("Content-Disposition: attachment;filename=\"search_results.csv\""); 

if($_POST['data']){
  print $_POST['data'];
}
4

3 回答 3

1

试试这个它正在工作

$.ajax({
  type: "POST",
  url: "http://localhost/export/some.php",
  data: { dataString: "hi" },
  cache: false,
  success: function(data){
    alert(data);
    this.openDestinationURL();    
  }
});

这是php文件

<?php
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="sample.csv"');
$data =$_POST["dataString"];

$fp = fopen('php://output', 'w');//set the path
fputcsv($fp, $data);
fclose($fp);
?>
于 2013-08-12T09:42:35.517 回答
0

由于您正在发送data: { dataString: "hi" },实际的 POST 数据将是:

if(isset($_POST['dataString'])){
  print $_POST['dataString'];
}

也使用isset()。

至于你的 AJAX:

  $.ajax({
      type: "POST",
      url: "http://localhost/export/some.php",
      data: { dataString: "hi" },
      cache: false,
      success: function(result){
          alert(result);
          this.openDestinationURL();
      }
  });
于 2013-08-12T09:48:20.030 回答
0

将数据作为多维数组发送

$.post('http://localhost/export/some.php', 
    {data: [["aaa","bbb","ccc","dddd"],["123","456","789"],["aaa","bbb"]]}, 
    function(){
        alert('saved');
    }
);

在 php 端只需保存到文件

$output = fopen('path to csv file', 'w');
foreach ($_POST['data'] as $row) {
    fputcsv($output, $row, ';');
}
fclose($output);
于 2013-08-12T09:57:29.863 回答