将数据从js传递到php,并下载创建的csv文件。

时间:2023-01-31 15:12:15

I must pass array from JS to PHP using $.post(), create file using array and download it.

我必须使用$.post()将数组从JS传递到PHP,使用数组创建文件并下载它。

Using this pass array:

使用这个传递数组:

$('#csv').click(function () {
$.post(
    window.location + "crawler/save_to_file",
    {
        dane: wynik //array
    });
  });

Now in PHP using this:

在PHP中

$tablica=$_POST['dane'];
 $filename = "export-to-csv.csv";
                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                header("Content-type: text/csv");
                header("Content-Disposition: attachment; filename=\"$filename\"");
                header("Expires: 0");
                $fh = fopen( 'php://output', 'w' );
                $heading = false;
                if(!empty($tablica))
                    foreach($tablica as $row) {
                        if(!$heading) {
                            fputcsv($fh, array_keys($row));
                            $heading = true;
                        }
                        fputcsv($fh, array_values($row));
              }
                fclose($fh);

But when click on button to create and download file, nothing happens.

但是当点击按钮来创建和下载文件时,什么也没有发生。

Thanks

谢谢

CODE UPDATE

代码更新

JS file:

JS文件:

   $.ajax({
        url: window.location + "crawler/",
        type: "POST",
        dataType: "json",
        data: {
            wartosc: zmienna
        },
        success: function (odp) {
            wynik = odp;  //array
            tab = JSON.stringify(odp);
            $.post(window.location + "crawler/return_data",
                {
                    data: tab
                },
                function (data) {
                    $('#wynik').html(data);
                    $('.pobierz').show();
                }
            )
        }
    })


$('.button').click(function() {
    var $form = $('<form action="' + window.location + 'crawler/save_to_csv" method="post"></form>');
    $.each(wynik, function() {
        $('<input type="hidden" name="dane[]">').attr('value', this).appendTo($form);
    });
    $form.appendTo('body').submit();
});

And var_dump array in PHP file:

PHP文件中的var_dump数组:

function save_to_csv()
{
    $tablica=$_GET['dane'];
    var_dump($tablica);

}

return: "Undefined index: dane"

返回:“未定义的指数:丹麦人”

EDIT

编辑

$tablica must be $_POST not $_GET

$tablica必须是$_POST,而不是$_GET

2 个解决方案

#1


2  

This can be done with AJAX but you need to use the File api. So you do something like this:

这可以通过AJAX实现,但是需要使用文件api。你可以这样做:

$.post("csv.php", {
     dane: wynik //array
}, function(response){
   var blob = new Blob([response], { type:'text/csv' });
   alert(URL.createObjectURL(blob));
});

The url you get from the alert, contains your csv file.

您从警报中获得的url包含您的csv文件。

And of course if you want to go directly to the file you replace the alert with:

当然,如果你想直接进入文件,你可以将警告替换为:

window.location.href=URL.createObjectURL(blob);

UPDATE

更新

If you want to use a custom filename, there is a way to mask the url generated by URL.createObjectURL(), by using an a element. We than can use the new HTML5 attribute download which allows us to mask the url.

如果您想使用自定义文件名,可以使用一个元素来屏蔽url . createobjecturl()生成的url。我们不能使用新的HTML5属性下载,它允许我们屏蔽url。

Here is the updated code:

更新后的代码如下:

$.post("csv.php", {
     dane: wynik //array
}, function(response){
   var blob = new Blob([response], { type:'text/csv' }),
       a    = document.createElement('a'),
       url  = URL.createObjectURL(blob);

    // Put the link somewhere in the body
    document.body.appendChild(a);
    a.innerHTML = 'download me';
    a.href = url;
    // Set our custom filename
    a.download = 'myfilename.csv';
    // Automatically click the link 
    a.click();
});

#2


0  

Are you forced to use AJAX to send that array to your PHP code? If yes, it is not really possible.

您是否*使用AJAX将该数组发送到PHP代码?如果是,那是不可能的。

If not, instead of your AJAX call, you could build a hidden form with hidden inputs containing your array items and submit it via JavaScript.

如果不是,那么可以使用包含数组项的隐藏输入构建隐藏表单,并通过JavaScript提交。

UPDATE Short example for form built with JS:

更新用JS构建的表单的简短示例:

$('#csv').click(function() {
  var $form = $('<form action="' + window.location + 'crawler/save_to_file" method="post"></form>');
  $.each(wynik, function() {
    $('<input type="hidden" name="dane[]">').attr('value', this).appendTo($form);
  });
  $form.appendTo('body').submit();
});

#1


2  

This can be done with AJAX but you need to use the File api. So you do something like this:

这可以通过AJAX实现,但是需要使用文件api。你可以这样做:

$.post("csv.php", {
     dane: wynik //array
}, function(response){
   var blob = new Blob([response], { type:'text/csv' });
   alert(URL.createObjectURL(blob));
});

The url you get from the alert, contains your csv file.

您从警报中获得的url包含您的csv文件。

And of course if you want to go directly to the file you replace the alert with:

当然,如果你想直接进入文件,你可以将警告替换为:

window.location.href=URL.createObjectURL(blob);

UPDATE

更新

If you want to use a custom filename, there is a way to mask the url generated by URL.createObjectURL(), by using an a element. We than can use the new HTML5 attribute download which allows us to mask the url.

如果您想使用自定义文件名,可以使用一个元素来屏蔽url . createobjecturl()生成的url。我们不能使用新的HTML5属性下载,它允许我们屏蔽url。

Here is the updated code:

更新后的代码如下:

$.post("csv.php", {
     dane: wynik //array
}, function(response){
   var blob = new Blob([response], { type:'text/csv' }),
       a    = document.createElement('a'),
       url  = URL.createObjectURL(blob);

    // Put the link somewhere in the body
    document.body.appendChild(a);
    a.innerHTML = 'download me';
    a.href = url;
    // Set our custom filename
    a.download = 'myfilename.csv';
    // Automatically click the link 
    a.click();
});

#2


0  

Are you forced to use AJAX to send that array to your PHP code? If yes, it is not really possible.

您是否*使用AJAX将该数组发送到PHP代码?如果是,那是不可能的。

If not, instead of your AJAX call, you could build a hidden form with hidden inputs containing your array items and submit it via JavaScript.

如果不是,那么可以使用包含数组项的隐藏输入构建隐藏表单,并通过JavaScript提交。

UPDATE Short example for form built with JS:

更新用JS构建的表单的简短示例:

$('#csv').click(function() {
  var $form = $('<form action="' + window.location + 'crawler/save_to_file" method="post"></form>');
  $.each(wynik, function() {
    $('<input type="hidden" name="dane[]">').attr('value', this).appendTo($form);
  });
  $form.appendTo('body').submit();
});