为什么我的ajax请求总是抛出错误?
问题描述:
这里是我的代码:为什么我的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
部分执行。我的意思是它总是提醒wrong
。我该如何解决它?我正在试图做一个.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();
});
});
+0
谢谢..只是你能写出完整的代码吗? – stack
答
基本上阿贾克斯通常不用于文件下载,但你可以调整,使其感觉,这就是你所做的唯一的事情是当请求成功时我们从JavaScript的“document.location”功能弹出一个新窗口下载文件。除了为你所得到的错误,请尝试用最重要的PHP头如
header('Content-Type: text/plain');
header('Content-Disposition: attachment;filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
ob_clean();
flush();
readfile($fileName);
exit;
开始用你的PHP头玩耍调试你的PHP代码检查你的代码可与最少的信息,如果它工作,然后开始添加更多头一个一个,这有助于以最少的信息解决问题。 希望这有助于。
什么在您的export.txt文件中? –