Ajax和下载CSV文件 [英] Ajax and downloading CSV file

查看:408
本文介绍了Ajax和下载CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ajax构建导出为CSV"系统,因此 这是我的ajax电话

I'm trying to build a "Export to CSV" system using ajax so this is my ajax call

$(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);
        }
    });
});

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

and this is my php code to convert an array to csv

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返回成功,但现在我陷入困境...

Everything is working. My ajax returns success but now I'm stuck...

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

How to download the file after a successfully ajax call? What is the next step?

我已经进行了研究,没有发现任何相关和/或有用的东西.

I already did my research and I found nothing relevant and/or helpful.

谢谢.

推荐答案

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

Return the url of the .csv file in your ajax call. Then in your success function put:

location.href = url;

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

Just like all file types that are not naturally handled by the browser this will cause the browser to download the file.

这篇关于Ajax和下载CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆