我是 Grails 的新手,在下载 Controller 中生成的文档时遇到了麻烦。
我的 jQuery
$("#exportAllSelectedData").click(function() {
var dataToExport = $("#dataToExport").val();
jQuery.ajax(
{type:'POST',
data:'dataToExport=' + dataToExport ,
dataType: 'json',
url:'/myapp/mycontroller/exportPreferences'});;
});
我的 Controller
def exportPreferences ()
{
File file = File.createTempFile("export",".xml");
String dataToWrite = params.dataToExport;
file.write(dataToWrite);
response.contentType = "application/octet-stream";
response.setHeader "Content-disposition", "attachment; filename=${file.name}";
response.outputStream << file.bytes;
response.outputStream.flush();
}
我期待用我的浏览器下载 outputStream 但什么也没发生。
我究竟做错了什么 ?
编辑 :
谢谢拉胡尔。
它适用于:
$("#exportAllSelectedData").click(function() {
var dataToExport = $("#dataToExport").val();
window.location="<g:createLink controller="mycontroller"
action="exportPreferences"/>"+"?dataToExport="+dataToExport
});
最佳答案
您不需要 Ajax 来下载文件。
您可以简单地使用 window.location
下载您的文件。
示例:
$("#exportAllSelectedData").click(function() {
window.location="<g:createLink controller="mycontroller" action="exportPreferences" />"
});
如果您尝试使用 Ajax,您将获得(渲染)文件文本
示例:
$("#exportAllSelectedData").click(function() {
$.ajax({
type: "GET",
url: "<g:createLink controller="demo" action="exportPreferences" />",
success: function (data) {
console.log(data);
}
});
});
希望这会帮助你。
关于ajax - 在 Ajax 中调用 Controller 以在 Grails 中下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49820510/