繁体   English   中英

如何在WordPress中使用AJAX发送文件下载?

[英]How do I send a file to download with AJAX in WordPress?

我正在尝试削减WordPress的插件。 请帮助🙂将JavaScript数据从后端获取并返回给PHP,后者在服务器上创建一个文件。 任务是在浏览器中将其提供给用户。 老脚本没有问题下载了它.php:

header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename='$name;');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($name));
if (ob_get_contents()) ob_end_clean();
flush();
readfile($name);

但为了安全起见,您必须禁止直接访问,确定:

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

因此,成功的AJAX调用开始打开一个空窗口:

$.ajax ( {

    type: "POST",

    url: myAyax.ajax_urls.write_url,//Here, the function hooked via the hook to admin-ajax.php is called

    data: {
        ids: [], //This is some kind of data
        action: 'write_file_server', //We pass the hook. Who writes a file with data to the server.
    },

    success: function ( result ) {
        window.location = myAyax.ajax_urls.download_url //Here was a link to the direct call download.php (see above)
    }

} );

试图通过钩子引起的功能:include('download.php'); 调用,将内容和代码发送到缓冲区200,但不会摇摆;)文件中的成功链接打开其内容,当然也不会摇摆🙂请帮忙。

我清理了你的javascript格式,它似乎对我有用。 那是你在找什么?

$.ajax ( {

    type: "POST",

    url: myAyax.ajax_urls.write_url,//Here, the function hooked via the hook to admin-ajax.php is called

    data: {
        ids: [], //This is some kind of data
        action: 'write_file_server', //We pass the hook. Who writes a file with data to the server.
    },

    success: function ( result ) {
        window.location = myAyax.ajax_urls.download_url //Here was a link to the direct call download.php (see above)
    }

} );

我找到了一个解决方案:)我需要在Get请求上做一个钩子,并用链接调用它:

window.location = window.location.href+'&filename=file.file';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM