Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用ajax和php加载文件_Php_Jquery_Ajax - Fatal编程技术网

使用ajax和php加载文件

使用ajax和php加载文件,php,jquery,ajax,Php,Jquery,Ajax,在我的html中,我有 $('#vcc').click(function() { get_file() } ); function get_file() { $.ajax({ url: "test.php",context: document.body}) .done(function(text) { .... }); } 在test.php中,我正在生成一个pdf文档 header('Content-Description: File Tra

在我的html中,我有

$('#vcc').click(function() { get_file() } );

function get_file()
{
    $.ajax({ url: "test.php",context: document.body})
    .done(function(text)
    {
    ....
    });
}
test.php
中,我正在生成一个pdf文档

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header("Content-Type: application/force-download");
    header('Content-Disposition: attachment; filename=' . urlencode(basename("factures/facture_2015_03.pdf")));
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . strlen($response));

    ob_clean();
    flush();
    echo $response;
如果我直接调用test.php,它就工作了,文件就被下载了

现在我想让它与ajax调用一起工作。但是我不知道在
中放什么…
我试着用
文档写。pdf文件的内容显示在我的浏览器中,但未下载

我能做什么


编辑:

现在我的
local.php
包含

<html>

<head>
    <script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
    <script type="text/javascript">

    $( document ).ready(function() { document_ready(); } );

    function document_ready()
    {
        $('#vcc').click(function() { get_ajax() } );

        $.ajaxTransport("+binary", function(options, originalOptions, jqXHR)
        {
            // check for conditions and support for blob / arraybuffer response type
            if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob)))))
            {
                return {
                        // create new XMLHttpRequest
                        send: function(_, callback){
                            // setup all variables
                            var xhr = new XMLHttpRequest(),
                                url = options.url,
                                type = options.type,
                                // blob or arraybuffer. Default is blob
                                dataType = options.responseType || "blob",
                                data = options.data || null;

                            xhr.addEventListener('load', function(){
                                var data = {};
                                data[options.dataType] = xhr.response;
                                // make callback and send data
                                callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
                            });

                            xhr.open(type, url, true);
                            xhr.responseType = dataType;
                            xhr.send(data);
                        },
                        abort: function(){
                            jqXHR.abort();
                        }
                    };
                }
            });
        }

        function get_ajax()
        {
            $.ajax({
                  url: "remote.php",
                  // data that you want send to PHP script
                  data: { fileId: "random", extraData: "some value" },
                  type: "GET", // or POST
                  dataType: "binary", // make our special transfer type
                  processData: false,
                  success: function(text)
                  {
                  var pdfContent = [text]; // change to Array
                  var fakeFile= new Blob(pdfContent, {type: 'application/pdf'});
                  SaveToDisk(fakeFile, "form1.pdf")
                  }
                });
        }

        function SaveToDisk(blobURL, fileName) {
            var reader = new FileReader();
            reader.readAsDataURL(blobURL);
            reader.onload = function (event) {
                var save = document.createElement('a');
                save.href = event.target.result;
                save.target = '_blank';
                save.download = fileName || 'unknown file';

                var event = document.createEvent('Event');
                event.initEvent('click', true, true);
                save.dispatchEvent(event);
                (window.URL || window.webkitURL).revokeObjectURL(save.href);
            };
        }

    </script>
</head>

<body>

<div>
    <input type="submit" id="vcc" value="Go"></input>
</div>

</body>
结果呢


无法使用JavaScript/JQuery下载文件,原因很简单,因为他们无法在客户端创建文件
您可以放置一个链接来下载您的文件

<a href="test.php">Download file </a>

您不能使用JavaScript/JQuery下载文件,原因很简单,因为他们无法在客户端创建文件
您可以放置一个链接来下载您的文件

<a href="test.php">Download file </a>

您可以在新的浏览器中创建文件(即仅10+、全Chrome、Firefox、Safari..)

保存生成的文件的代码:

function SaveToDisk(blobURL, fileName) {
    var reader = new FileReader();
    reader.readAsDataURL(blobURL);
    reader.onload = function (event) {
        var save = document.createElement('a');
        save.href = event.target.result;
        save.target = '_blank';
        save.download = fileName || 'unknown file';

        var event = document.createEvent('Event');
        event.initEvent('click', true, true);
        save.dispatchEvent(event);
        (window.URL || window.webkitURL).revokeObjectURL(save.href);
    };
}
生成文件的代码:

var pdfContent = ['file content']; // create Array bytes of file or with it's content as string
var fakeFile= new Blob(pdfContent, {type: 'application/pdf'});
强制浏览器将其保存在光盘上:

SaveToDisk(fakeFile, "my.pdf")

编辑:

PDF文件和其他许多文件一样,都是“二进制”格式,这在JS中不是默认格式,但jQuery让我们制作“插件”来添加类似的新功能(传输二进制文件,完整教程:)

在“jQuery加载之后”和“AJAX调用之前”的某处添加:

$.ajaxTransport("+binary", function(options, originalOptions, jqXHR){
    // check for conditions and support for blob / arraybuffer response type
    if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob)))))
    {
        return {
            // create new XMLHttpRequest
            send: function(_, callback){
                // setup all variables
                var xhr = new XMLHttpRequest(),
                    url = options.url,
                    type = options.type,
                    // blob or arraybuffer. Default is blob
                    dataType = options.responseType || "blob",
                    data = options.data || null;

                xhr.addEventListener('load', function(){
                    var data = {};
                    data[options.dataType] = xhr.response;
                    // make callback and send data
                    callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
                });

                xhr.open(type, url, true);
                xhr.responseType = dataType;
                xhr.send(data);
            },
            abort: function(){
                jqXHR.abort();
            }
        };
    }
});
ajax调用应该如下所示[记住在上面的代码中添加函数SaveToDisc

$.ajax({
  url: "generate/pdf/test.php",
  // data that you want send to PHP script
  data: { fileId: "random", extraData: "some value" },
  type: "GET", // or POST
  dataType: "binary", // make our special transfer type
  processData: false,
  success: function(text){
  var pdfContent = [text]; // change to Array
  var fakeFile= new Blob(pdfContent, {type: 'application/pdf'});
  SaveToDisk(fakeFile, "myPdfDownloader.pdf")
  }
});

我又做了一次测试,它对我有效。我希望你现在可以接受我的回答:)

你可以在新的浏览器中创建文件(即仅10+,全是Chrome、Firefox、Safari..)

保存生成的文件的代码:

function SaveToDisk(blobURL, fileName) {
    var reader = new FileReader();
    reader.readAsDataURL(blobURL);
    reader.onload = function (event) {
        var save = document.createElement('a');
        save.href = event.target.result;
        save.target = '_blank';
        save.download = fileName || 'unknown file';

        var event = document.createEvent('Event');
        event.initEvent('click', true, true);
        save.dispatchEvent(event);
        (window.URL || window.webkitURL).revokeObjectURL(save.href);
    };
}
生成文件的代码:

var pdfContent = ['file content']; // create Array bytes of file or with it's content as string
var fakeFile= new Blob(pdfContent, {type: 'application/pdf'});
强制浏览器将其保存在光盘上:

SaveToDisk(fakeFile, "my.pdf")

编辑:

PDF文件和其他许多文件一样,都是“二进制”格式,这在JS中不是默认格式,但jQuery让我们制作“插件”来添加类似的新功能(传输二进制文件,完整教程:)

在“jQuery加载之后”和“AJAX调用之前”的某处添加:

$.ajaxTransport("+binary", function(options, originalOptions, jqXHR){
    // check for conditions and support for blob / arraybuffer response type
    if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob)))))
    {
        return {
            // create new XMLHttpRequest
            send: function(_, callback){
                // setup all variables
                var xhr = new XMLHttpRequest(),
                    url = options.url,
                    type = options.type,
                    // blob or arraybuffer. Default is blob
                    dataType = options.responseType || "blob",
                    data = options.data || null;

                xhr.addEventListener('load', function(){
                    var data = {};
                    data[options.dataType] = xhr.response;
                    // make callback and send data
                    callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
                });

                xhr.open(type, url, true);
                xhr.responseType = dataType;
                xhr.send(data);
            },
            abort: function(){
                jqXHR.abort();
            }
        };
    }
});
ajax调用应该如下所示[记住在上面的代码中添加函数SaveToDisc

$.ajax({
  url: "generate/pdf/test.php",
  // data that you want send to PHP script
  data: { fileId: "random", extraData: "some value" },
  type: "GET", // or POST
  dataType: "binary", // make our special transfer type
  processData: false,
  success: function(text){
  var pdfContent = [text]; // change to Array
  var fakeFile= new Blob(pdfContent, {type: 'application/pdf'});
  SaveToDisk(fakeFile, "myPdfDownloader.pdf")
  }
});

我又做了一次测试,它对我有效。我希望您现在可以接受我的回答:)

我假设您在单击链接或文本div下载文档时,不希望该页面指向该php文件,相反,您希望该页面位于同一页面中,而不会通过JQUERY路由到另一个页面。您需要在JQUERY中调用ajax方法。 确保您包含了经过更正和更新的JQuery库。然后假设您希望通过ajax下载名为“ozan”的文档。然后我假设文档中的文本为“ozan”,然后在JQuery中您可以将其编写为:

$(document).ready(function(){
$("#document_name").click(function(){
var documentname=$(this).val();
$.ajax({method:"POST",
url:"test.php",
data:{name:documentname},
success:function(incoming){`
alert("Downloading...");
}
});});
当您创建ajax时,它将在test.php中自动发送文档名,而不刷新页面,然后在该php中获取值,如下所示:

if(isset($_POST["name"])){
$document_name=$_POST["name"];
}
然后,您可以在php文件中的代码段下面编写下载代码


我假设您在单击链接或文本div下载文档时,不希望页面指向该php文件,相反,您希望页面位于同一页面中,而不通过JQUERY路由到另一页面。您需要在JQUERY中调用ajax方法。 确保您包含了经过更正和更新的JQuery库。然后假设您希望通过ajax下载名为“ozan”的文档。然后我假设文档中的文本为“ozan”,然后在JQuery中您可以将其编写为:

$(document).ready(function(){
$("#document_name").click(function(){
var documentname=$(this).val();
$.ajax({method:"POST",
url:"test.php",
data:{name:documentname},
success:function(incoming){`
alert("Downloading...");
}
});});
当您创建ajax时,它将在test.php中自动发送文档名,而不刷新页面,然后在该php中获取值,如下所示:

if(isset($_POST["name"])){
$document_name=$_POST["name"];
}
然后,您可以在php文件中的代码段下面编写下载代码


您只需设置具有下载属性的下载按钮:


您只需设置带有下载属性的下载按钮:


我不确定[我的另一个jQuery解决方案在Firefox中不起作用..]。正如许多其他人所说,您不应该使用AJAX/jQuery使web浏览器下载文件

例如:

page.htm带有下载链接/按钮/任何内容:

<!doctype html>
<html>
<head>
    <title>Download fake file from JS script example</title>
    <meta charset="utf-8">
    <script>
function downloadPdfExample()
{
    // simple :)
    window.location = "download_pdf.php";
}
    </script>
</head>
<body>
Click on button below to start download:<br />
<button onclick="downloadPdfExample()">Start PDF download</button><br />

</body>
</html>
抛出错误!发送文件内容后无法设置响应标头(readfile将文件内容发送到浏览器,而不是将其放入变量$response!)


$response中是发送到浏览器的数据长度,所以strlen($response)也不起作用。

我不确定[我的另一个jQuery解决方案在Firefox中不起作用..]。正如许多其他人所说,您不应该使用AJAX/jQuery使web浏览器下载文件

例如:

page.htm带有下载链接/按钮/任何内容:

<!doctype html>
<html>
<head>
    <title>Download fake file from JS script example</title>
    <meta charset="utf-8">
    <script>
function downloadPdfExample()
{
    // simple :)
    window.location = "download_pdf.php";
}
    </script>
</head>
<body>
Click on button below to start download:<br />
<button onclick="downloadPdfExample()">Start PDF download</button><br />

</body>
</html>
抛出错误!发送文件内容后无法设置响应标头(readfile将文件内容发送到浏览器,而不是将其放入变量$response!)


$response中是发送到浏览器的数据长度,所以strlen($response)也不起作用。

是否有说明为什么不使用具有下载属性的普通链接?这是因为pdf文件仅在我发送ajax请求时生成。并且未保存在服务器上。是否发送POST参数?否则,您可以简单地链接到test.phpIs。是否有一个说明为什么不使用具有下载属性的普通链接?这是因为pdf文件仅在我发送ajax请求时生成。并且未保存在服务器上。是否发送POST参数?否则,您可以简单地链接到test.phpI,我正在尝试您的解决方案。我已经把上面的三行放在了。完成了。但什么也没发生。我的问题是ajax调用,我应该在pdfContent中添加什么?var pdfContent=test?我添加了更多信息并测试了PDF传输(必须是二进制的,如果没有二进制传输,它将创建一个充满空白页面的大PDF文件)。在test.php中,您必须生成可通过浏览器查看的PDF文件内容。有了所有这些“jQuery传输”更改,它应该可以工作,即使您