使用 Ajax 下载 JQuery 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11163008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery file download with Ajax
提问by Jason Wells
I'm using John Culviner's great fileDownload plugin to produce a "please wait" message when my user chooses to generate a report.
当我的用户选择生成报告时,我正在使用 John Culviner 的出色 fileDownload 插件来生成“请稍候”消息。
When a user clicks a link, I send an ajax request to my PHP which generates a PDF on the server. At that point I am attempting to update the link in my success handler for the fileDownload plugin.
当用户单击链接时,我向我的 PHP 发送一个 ajax 请求,该请求在服务器上生成一个 PDF。那时我正在尝试更新我的成功处理程序中 fileDownload 插件的链接。
I may be approaching this wrong, but here's my code - any help is greatly appreciated.
我可能正在接近这个错误,但这是我的代码 - 非常感谢任何帮助。
$("body").on("click","##pdfLink", function(e){
$.fileDownload($(this).attr('href'), {
preparingMessageHtml: "Preparing your report, please wait...",
failMessageHtml: "There was a problem generating your report, please try again."
});
// Build our data string.
var strData = {method: "createPDF"};
// Send a request to build our XL file.
$.ajax({
url: '/pdf.php',
data: strData,
type: 'get',
dataType: 'json',
success: function(data) {
alert(data);
$("##pdfLink").attr("href","/pdf/"+data);
},
error: function(e) {
console.log(e);
}
});
return false;
e.preventDefault();
})
At this point, when I click the link the modal is displayed correctly with the "Please Wait" message. My file does get built on the server (Confirmed with my alert in my success handler), and my HREF does get updated. However, the plugin does not prompt the user for download.
此时,当我单击链接时,模态会正确显示,并带有“请稍候”消息。我的文件确实建立在服务器上(通过我的成功处理程序中的警报确认),并且我的 HREF 确实得到了更新。但是,该插件不会提示用户下载。
Thanks!
谢谢!
回答by Engineer
Probably , you need to start download ,after link's reference will be received:
可能,您需要开始下载,在收到链接的参考后:
$("body").on("click","##pdfLink", function(e){
// Build our data string.
var strData = {method: "createPDF"};
var self = this;
var $pdfGeneratingDialog = $('<div>',{
title:"Generating PDF",
text: "Please wait..."
}).dialog({modal:true});
// Send a request to build our XL file.
$.ajax({
url: '/pdf.php',
data: strData,
type: 'get',
dataType: 'json',
success: function(data) {
$pdfGeneratingDialog.dialog('close');
alert(data);
$(self).attr("href","/pdf/"+data);
//starting download process
$.fileDownload($(self).attr('href'), {
preparingMessageHtml: "Preparing your report, please wait...",
failMessageHtml: "There was a problem generating your report, please try again."
});
},
error: function(e) {
console.log(e);
}
});
return false;
});
回答by Jones
You not need call ajax funcion in JS. Your link <a href='yoursite.com/pdf.php'
identify with this command $(this).attr('href')
location of you server process of pdf.
你不需要在 JS 中调用 ajax 函数。您的链接<a href='yoursite.com/pdf.php'
与$(this).attr('href')
您的 pdf 服务器进程的此命令位置一致。
EDIT:
编辑:
Your call:
您的来电:
// Build our data string.
var strData = {method: "createPDF"};
var $preparingFileModal = $("#preparing-file-modal");
$preparingFileModal.dialog({ modal: true });
$.fileDownload($(this).attr('href'), {
httpMethod: "GET",
data: strData
successCallback: function (responseHtml, url) {
$preparingFileModal.dialog('close');
// In this case
$.fileDownload("/pdf/"+responseHtml, {
preparingMessageHtml: "Download file",
failMessageHtml: "Not work"
});
},
failCallback: function (responseHtml, url) {
$preparingFileModal.dialog('close');
$("#error-modal").dialog({ modal: true });
}
});
HTML:
HTML:
<div id="preparing-file-modal" title="Preparing report..." style="display: none;">
We are preparing your report, please wait...
<div class="ui-progressbar-value ui-corner-left ui-corner-right" style="width: 100%; height:22px; margin-top: 20px;"></div>
</div>
<div id="error-modal" title="Error" style="display: none;">
There was a problem generating your report, please try again.
</div>
回答by datnt
I also use jquery.filedownload for my app, I hope my solution would help someone else who has the similar requirement with me; and I change the usage just a little bit. i.e:
我也将 jquery.filedownload 用于我的应用程序,我希望我的解决方案能帮助与我有类似需求的其他人;我只是稍微改变了用法。IE:
I use it with rails3
I want to display tweeter bootstrap modal instead of jquery's Dialog.
我将它与 rails3 一起使用
我想显示高音引导程序模式而不是 jquery 的对话框。
A.The client side (front-ent), below is the function that support for download file when user click on the file item on HTML page:
A.客户端(front-ent),下面是支持用户点击HTML页面文件项时下载文件的功能:
function DownloadFile(id, file_url, file_name, strTime){
函数下载文件(id,file_url,file_name,strTime){
$.fileDownload(file_url, {
successCallback: function (url) {
$("#ilulModaldow").find('#file_name').html(file_name);
$("#ilulModaldow").find('#file_created_at').html(strTime);
$("#ilulModaldow").modal();
//DATNT comment: $("#ilulModaldow") is a normal tweeter modal
},
failCallback: function (html, url) {
alert('Connection error! Please try again');
}
});
}
}
B.server side (back-end), I created an action to send file, this action is the paramenter "file_url" of the javascript function above:
B.服务器端(后端),我创建了一个发送文件的动作,这个动作是上面javascript函数的参数“file_url”:
def download
高清下载
a=APostAttach.find(params[:id])
send_file a.file.path(:original), :type => a.file_content_type
#DATNT comment: below is the way I set cookies for jquery.filedownload plugin requirement
cookies[:fileDownload] = true
cookies[:Path] = "/"
end
结尾
C.combine back-end and font-end based on item(file) click event:
C.根据item(file)点击事件结合back-end和font-end:
$('#attach_<%= attach.id %>').click(function(){
DownloadFile("<%= attach.id %>","<%= download_courses_path(:id => attach.id) %>","<%=attach.file_file_name %>","Uploaded at <%= time_ago_in_words(attach.created_at).gsub('about','') + ' ago'%>");
});
回答by infografnet
I'm using the following code to download a file in same window (without opening new tab). It works, although it doesn't have any error support...
我正在使用以下代码在同一窗口中下载文件(无需打开新标签)。它有效,虽然它没有任何错误支持......
function downloadURL(url, callback) {
var id = 'hiddenDownloader';
$('body').append('<iframe id="' + id + '" style="display: block" src="' + url + '"></iframe>');
var $iframe = $('#' + id);
$iframe.on('load', function () {
$iframe.remove();
// no error support
callback();
});
}
downloadURL('http://example.com', function() {
alert('Done');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
回答by John Macon
have you tried adjusting your timeout?
您是否尝试过调整超时时间?
$.ajax({
url: '/pdf.php',
data: strData,
type: 'get',
dataType: 'json',
timeout: 10000,
success: function(data) {
alert(data);
$("##pdfLink").attr("href","/pdf/"+data);
},
error: function(e) {
console.log(e);
}
});
return false;
e.preventDefault();