调用 Ajax 中的控制器以在 Grails 中下载文件
Call controller in Ajax to download a file in Grails
我是 Grails 的新手,我在下载在我的控制器中生成的文档时遇到了问题。
我的jQuery
$("#exportAllSelectedData").click(function() {
var dataToExport = $("#dataToExport").val();
jQuery.ajax(
{type:'POST',
data:'dataToExport=' + dataToExport ,
dataType: 'json',
url:'/myapp/mycontroller/exportPreferences'});;
});
我的控制器
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);
}
});
});
希望对您有所帮助。
我是 Grails 的新手,我在下载在我的控制器中生成的文档时遇到了问题。
我的jQuery
$("#exportAllSelectedData").click(function() {
var dataToExport = $("#dataToExport").val();
jQuery.ajax(
{type:'POST',
data:'dataToExport=' + dataToExport ,
dataType: 'json',
url:'/myapp/mycontroller/exportPreferences'});;
});
我的控制器
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);
}
});
});
希望对您有所帮助。