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

时间:2017-03-11 11:30:36

标签: javascript php jquery ajax 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,但不会摇摆;) 文件中的succes-e链接打开了它的内容,当然也没有摆动 请帮忙。

2 个答案:

答案 0 :(得分:0)

我清理了你的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)
    }

} );

答案 1 :(得分:0)

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

tf.nn.dynamic_rnn