javascript - 为什么我的 ajax 请求总是抛出错误?

标签 javascript php jquery ajax

这是我的代码:

PHP:

public function export(Request $request){

    $file = "export.txt";
    if(isset($_POST["type"])){
        file_put_contents("$file",$_POST["text"]);
    }
    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: text/plain'); // the appropriate header type for txt file
        header('Content-Disposition: attachment; filename="'.basename($file).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    }
}

JS:

    $(document).on('click', '#export', function () {
        var names =  ['علی','فرید'];
        var namess = names.join('\n');
        $.ajax({
            type: "post",
            url: "/export",
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: {
                type: "save",
                text: namess
            },
            dataType: "json",
            success: function(){
                var href = '/export?filename=export.txt';
                window.location = href;
            },
            error: function(){
                alert('wrong');
            }
        });
    })

总是 error 部分执行。我的意思是它总是警告 错误。我该如何解决?我正在努力制作一个 .txt 下载文件。

注意到当我运行此路径时:http://localhost:8000/export?filename=export.txt .. 然后将下载 export.txt

最佳答案

您可以使用此代码下载:

window.location="export?filename=export.txt";

如果你想发布数据:

   $('<form action="comments.php" method="POST"/>')
        .append($('<input type="hidden" name="type" value="save">'))
       .append($('<input type="hidden" name="text" value="'+ namess +'">'))
        .appendTo($(document.body)) //it has to be added somewhere into the <body>
        .submit();

完整代码:

 $(document).on('click', '#export', function () {

    var names =  ['علی','فرید'];
    var namess = names.join('\n');

     $('<form action="export?filename=export.txt" method="POST"/>')
        .append($('<input type="hidden" name="type" value="save">'))
       .append($('<input type="hidden" name="text" value="'+ namess +'">'))
        .appendTo($(document.body)) //it has to be added somewhere into the <body>
        .submit();

    });

});

关于javascript - 为什么我的 ajax 请求总是抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40446877/

相关文章:

javascript - Node js 添加所需的模型

javascript - puppeteer 师找不到元素

javascript - 在雪花存储过程中,有没有办法检查结果集中有多少列?

php - 对数组进行连接操作

javascript - 如何使用 javascript 动态添加 html 元素并在 php 中保存它们的记录

javascript - 将日期字符串从 YYYYMMDD 转换为 DD Mon YYYY

javascript - 使用 switch 语句从另一个页面滚动到 anchor

javascript - Google Charts - 从 Ajax 创建数据

javascript - 如何使用 jQuery 显示文本框或表单已被编辑?

php - 尝试使用 PATCH 方法适用于 AJAX,但不适用于常规 html 表单