简体   繁体   English

使用jquery ajax post方法发布并触发服务器中的php文件

[英]post and trigger a php file in server using jquery ajax post method

send the values from a javascript file to server side php file and create a file in server side using the jquery ajax post method. 将值从javascript文件发送到服务器端php文件,并使用jquery ajax post方法在服务器端创建文件。

try some code 尝试一些代码

javascript code JavaScript代码

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

php code as below 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'];
}

Try this it is working 试试这个,它正在工作

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

here is the php file 这是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);
?>

Since you're sending data: { dataString: "hi" } , the actual POST data will be: 由于您要发送data: { dataString: "hi" } ,因此实际的POST数据将为:

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

Also use isset(). 还可以使用isset()。

As for your AJAX: 至于您的AJAX:

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

Send data as multidimensional array 将数据作为多维数组发送

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

On php side just save to file 在PHP方面只是保存到文件

$output = fopen('path to csv file', 'w');
foreach ($_POST['data'] as $row) {
    fputcsv($output, $row, ';');
}
fclose($output);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM