Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

php - Ajax and downloading CSV file

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

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(endJsonJson::encode(array('response' => true)));
    }
    return $this->getResponse()->setStatusCode(400);
}

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

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.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...