【问题标题】:Ajax and downloading CSV fileAjax 和下载 CSV 文件
【发布时间】:2015-10-28 16:34:30
【问题描述】:

我正在尝试使用 ajax 构建一个“导出到 CSV”系统,所以 这是我的ajax调用

$(document).on('click', '#export-csv', function(){
    $.ajax({
        url: export_url,
        type: 'post',
        data:{ validations: validations },
        dataType: 'json',
        cache: false,
        timeout: 1000000,
        success: function (data) {
            var resp = data.response;
            console.log(resp);
        },
        error: function (error) {
            console.log(error);
        }
    });
});

这是我将数组转换为 csv 的 php 代码

public function exportCsvAction()
{
    $request = $this->getRequest();
    if ($request->isPost()) {

        $input = $request->getPost();
        $response = $this->getResponse();

        $file = fopen('php://output', 'w');
        foreach ($input['validations'] as $line) {
            fputcsv($file, $line, chr(9), '"');
        }
        fclose($file);

        header('Content-type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="validations-' . time() . '.csv"');

        return $response->setContent(\Zend\Json\Json::encode(array('response' => true)));
    }
    return $this->getResponse()->setStatusCode(400);
}

一切正常。我的 ajax 返回成功,但现在我被卡住了......

ajax调用成功后如何下载文件?下一步是什么?

我已经进行了研究,但没有发现任何相关和/或有用的信息。

提前致谢。

【问题讨论】:

    标签: php jquery ajax zend-framework2


    【解决方案1】:

    在您的 ajax 调用中返回 .csv 文件的 url。然后在你的成功函数中输入:

    location.href = url;
    

    就像浏览器不能自然处理的所有文件类型一样,这将导致浏览器下载文件。

    【讨论】:

    • 这会再次重新加载整个文件,使 AJAX 加载变得多余。
    【解决方案2】:

    尝试使用URL.createObjectURLBlob创建href属性设置为文件的data URIa元素; download 属性为“保存文件”对话框设置文件名

    success: function (data) {
                var resp = data.response;
                var a = $("<a />", {
                   href: "data:text/csv," 
                         + URL.createObjectURL(new Blob([resp], {
                             type:"text/csv"
                           })),
                   "download":"filename.csv"
                });
                $("body").append(a);
                a[0].click();
            }
    

    【讨论】:

      【解决方案3】:

      它对我有用,完美。

       jQuery(document).on( 'click', '.btn_generate_product', function(e) {
      
      var product_id = jQuery(this).data('product_id');
      
      jQuery.ajax({
          url : "ajaxurl", 
          type: 'POST',
          data: { product_id },
          success: function(data){
      
                /*
                 * Make CSV downloadable
                 */
                var downloadLink = document.createElement("a");
                var fileData = ['\ufeff'+data];
      
                var blobObject = new Blob(fileData,{
                   type: "text/csv;charset=utf-8;"
                 });
      
                var url = URL.createObjectURL(blobObject);
                downloadLink.href = url;
                downloadLink.download = "products.csv";
      
                /*
                 * Actually download CSV
                 */
                document.body.appendChild(downloadLink);
                downloadLink.click();
                document.body.removeChild(downloadLink);
      
          }
      });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-27
        • 2023-03-16
        • 2019-10-27
        • 1970-01-01
        • 1970-01-01
        • 2018-02-21
        • 2017-06-13
        相关资源
        最近更新 更多