通过Ajax调用PHP下载文件

通过Ajax调用PHP下载文件

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

问题描述

我有一个按钮和的onclick 它会调用一个AJAX功能。

I have a button and onclick it will call an ajax function.

下面是我的AJAX功能

Here is my ajax function

function csv(){

    ajaxRequest = ajax();//ajax() is function that has all the XML HTTP Requests

    postdata = "data=" + document.getElementById("id").value;

    ajaxRequest.onreadystatechange = function(){
        var ajaxDisplay = document.getElementById('ajaxDiv');
        if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
            ajaxDisplay.innerHTML = ajaxRequest.responseText;
        }
    }

    ajaxRequest.open("POST","csv.php",false);
    ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajaxRequest.send(postdata);
}

我创建基于用户输入的csv文件。它的创建后,我希望它提示下载或强制下载(preferably力)。我使用下面的脚本在PHP文件的末尾来下载文件。如果我在一个单独的文件中运行此脚本,它工作正常。

I create the csv file based on the user input. After it's created I want it to prompt download or force download(preferably force). I am using the following script at the end of the php file to download the file. If I run this script in a separate file it works fine.

$fileName = 'file.csv';
$downloadFileName = 'newfile.csv';

if (file_exists($fileName)) {
    header('Content-Description: File Transfer');
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename='.$downloadFileName);
    ob_clean();
    flush();
    readfile($fileName);
    exit;
}
echo "done";

而不是下载,但如果我运行它csv.php年底它输出FILE.CSV的内容到页面(进入ajaxDiv)。

But If I run it at the end of csv.php it outputs the contents of the file.csv into the page(into the ajaxDiv) instead of downloading.

有没有办法来强制下载文件时csv.php的结束?

Is there a way to force download the file at the end of csv.php?

推荐答案

AJAX是不是下载文件。弹出一个新的窗口下载​​链接为它的地址,或做 document.location = ...

AJAX isn't for downloading files. Pop up a new window with the download link as its address, or do document.location = ....

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

08-05 09:24